<template>
  <a-spin :spinning="confirmLoading">
    <a-tabs defaultActiveKey="1" :activeKey.sync="activeKey" @change="tabsChange">
      <a-tab-pane tab="合同评审表" key="1">
        <j-form-container>
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="评审表编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                  <a-input v-model="model.code" placeholder="请输入评审表编号" :disabled="disabled"></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item
                  label="合同评审说明"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="contractCode"
                >
                  <a-input v-model="model.bussContractReviewDesRequire.code" disabled placeholder="请输入合同评审说明"></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowFlag">
                  <j-dict-select-tag
                    type="list"
                    :disabled="disabled"
                    v-model="model.flowFlag"
                    dictCode="contract_review_flow"
                    placeholder="请选择审批流程"
                  />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item
                  label="订单编号"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="schedulingNumber"
                >
                  <a-input
                    v-model="model.schedulingNumber"
                    placeholder="请输入订单编号"
                    :disabled="disabled"
                  ></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
                  <!--              <tsl-erp-customer v-model="model.customerId" @handlerok="changeCustomer"  :disabled="disabled"> </tsl-erp-customer>-->
                  <a-input v-model="model.bussContractReviewDesRequire.customerId_dictText" :disabled="disabled" @click="handleClick"> </a-input>
                  <TslSelectCustomer ref="selectCustomer" @selectOk="handleSelect" ></TslSelectCustomer>
                </a-form-model-item>
              </a-col>
              <!--              <a-col :span="2">
                              <a-button type="primary" icon="" size="small" @click="getSchedulingNumber">自动获取 </a-button>
                            </a-col>-->
              <a-col :span="8">
                <a-row>
                  <a-col :span="12">
                    <a-form-model-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
                      <!--              <a-input v-model="model.salesman" placeholder="请输入业务员"  :disabled="disabled"></a-input>-->
                      <j-dict-select-tag v-model="model.bussContractReviewDesRequire.salesman" dictCode="tsl_hr_employee_info,employee_name,id," placeholder="请输入业务员" disabled></j-dict-select-tag>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-model-item  label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customer">
                      <!--                      <a-input v-model="model.customer" placeholder="请输入客户类型"  :disabled="disabled"></a-input>-->

                      <j-dict-select-tag type="list"  dictCode="customer_category" v-model="model.bussContractReviewDesRequire.customer"  :disabled="disabled" placeholder="请选择客户类型" />

                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>



              <a-col :span="8">
                <a-form-model-item label="订货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
                  <a-row>
                    <a-col :span="20">

                      <a-input-number v-model="model.bussContractReviewDesRequire.weight" placeholder="请输入数量" style="width: 100%"  :disabled="disabled"/>
                    </a-col>
                    <a-col :span="4">
                      <j-dict-select-tag
                        type="list"
                        v-model="model.bussContractReviewDesRequire.weightUnit"
                        dictCode="zl_unit"
                        placeholder="请选择单位"
                      />
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>


              <a-col :span="8">
                <a-row>
                  <a-col :span="14">
                    <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payMethod">
                      <a-input v-model="model.bussContractReviewDesRequire.payMethod" :disabled="disabled" placeholder="请输入付款方式"></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="10">
                    <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currency">
                      <j-dict-select-tag
                        type="list"
                        :disabled="disabled"
                        @change="changeCurrency"
                        v-model="model.currency"
                        dictCode="currency"
                        placeholder="请选择币种"
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>


              <a-col :span="8">
                <a-row>
                  <a-col :span="10">
                    <a-form-model-item label="单价类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="priceType">
                      <j-search-select-tag @change="this.productQuotation" dict="price_type" v-model="model.priceType" :disabled="disabled"></j-search-select-tag>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="14">
                    <a-form-model-item label="交付日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryTime">
                      <a-input v-model="model.deliveryTime"  :disabled="disabled" placeholder="请输入交付日期"></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>

              </a-col>

              <a-col :span="8">
                <a-form-model-item label="是否确认版样" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isPattern">
                  <j-dict-select-tag
                    type="list"
                    :disabled="disabled"
                    v-model="model.isPattern"
                    dictCode="yes_no"
                    placeholder="请选择是否确认版样"
                  />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-row>
                  <a-col :span="14">
                    <a-form-model-item label="定金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deposit">
                      <a-input-number
                        v-model="model.deposit"
                        placeholder="请输入定金"
                        :disabled="disabled"
                        style="width: 100%"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="10">
                    <a-form-model-item
                      label="已到预付款"
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                      prop="advancePayment"
                    >
                      <a-input
                        v-model="model.advancePayment"
                        :disabled="disabled"
                        placeholder="请输入已到预付款"
                      ></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>



              <a-col :span="8">
                <a-row>
                  <a-col :span="10">
                    <a-form-model-item label="订货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractTime">
                      <!--                  <a-input v-model="model.contractTime" disabled placeholder="请输入订货日期"></a-input>-->
                      <j-date
                        placeholder="请选择订货日期"
                        class="query-group-cust"
                        :disabled="disabled"
                        v-model="model.contractTime"
                        style="width: 100%"
                      ></j-date>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="14">
                    <a-form-model-item label="价格执行表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bussMaterialPriceId">
                      <!--              <tsl-erp-customer v-model="model.customerId" @handlerok="changeCustomer"  :disabled="disabled"> </tsl-erp-customer>-->
                      <!--              <j-dict-select-tag type="list"  dictCode="buss_material_price,code,id" v-model="model.bussMaterialPriceId"  placeholder="请选择原料价格执行表" />-->
                      <j-search-select-tag
                        placeholder="请选择材料价格执行表"
                        v-model="model.bussMaterialPriceId"
                        :disabled="formDisabled||supplyDisabled"
                        style="width: 100%"
                        :dictOptions="dictOptions"
                        @change="onPriceExecuteChange">
                      </j-search-select-tag>
                    </a-form-model-item>
                  </a-col>
                </a-row>

              </a-col>

            </a-row>
            <a-row>
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="技术部" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
              <!--                  <a-textarea-->
              <!--                    v-model="model.technology"-->
              <!--                    :disabled="disabled"-->
              <!--                    :rows="8"-->
              <!--                    allow-clear-->
              <!--                    showCount-->
              <!--                  ></a-textarea>-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <a-col :span="8">
                <a-form-model-item label="技术部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.technologyHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.technology" />
                </a-form-model-item>
              </a-col>


              <a-col :span="8">
                <a-form-model-item label="供应部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.supplyHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.supply" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="质检部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.qualityHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.quality" />

                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="生产部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.produceHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.produce" />

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="包材核价" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.packagingPriceHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.packagingPrice" />

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="财务部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.financeHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.finance" />

                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="营销部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.marketingHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.marketing" />

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="营销总监评定结论" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div class="rich-text-container" :class="{ 'disabled': true }"  >
                    <div
                      v-html="model.conclusionHtml"
                      class="rich-text-content"
                    ></div>
                  </div>
                  <input type="hidden" v-model="model.conclusion" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea
                    v-model="model.remark"
                    :rows="8"
                    allow-clear
                    showCount
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="打码生产备注"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="productionRemark"
                >
                  <a-textarea
                    v-model="model.productionRemark"
                    :rows="8"
                    allow-clear
                    showCount
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <h4>附件列表</h4>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="bussContractReviewDesFilesTable.loading"
                  :columns="bussContractReviewDesFilesTable.columns"
                  :dataSource="bussContractReviewDesFilesTable.dataSource"
                  :maxHeight="300"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar="true"
                >
                  <template v-slot:action="{ row }">
                    <a @click="handlePreviewReviewDesFiles(row)">预览</a>
                  </template>
                </j-vxe-table>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>

      <a-tab-pane tab="产品及配方" key="2" forceRender>
        <j-form-container>
          <a-form-model ref="formProduct" :model="model" :rules="validatorRules" slot="detail">

            <!-- 子表单区域 -->
            <a-row :gutter="8" style="margin: 4px">
              <a-col :span="10" title="产品信息">
                <a-card class="mycard">
                  <!--                  <a-col :span="24">-->
                  <a-row :gutter="10">
                    <a-col :span="4">
                      <h4>产品信息</h4>
                    </a-col>
                    <a-col :span="2">
                      <!--                        <a-form-model-item>-->
                      <a-button :disabled="this.disabled" type="primary" icon="" size="small" @click="addGoods"> 新增产品 </a-button>
                      <!--                        </a-form-model-item>-->
                    </a-col>
                    <!--                      <a-col :span="12">
                                            <a-form-model-item
                                              label="辅数量合计"
                                              :labelCol="labelCol"
                                              :wrapperCol="wrapperCol"
                                              prop="totalProductAmount"
                                            >
                                              <a-input v-model="model.totalProductAmount" disabled placeholder="合计" style="width: 100%" />
                                            </a-form-model-item>
                                          </a-col>
                                          <a-col :span="8">
                                            <a-form-model-item label="订货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
                                              <a-input-number v-model="model.weight" disabled placeholder="请输入重量" />
                                            </a-form-model-item>
                                          </a-col>-->
                  </a-row>
                  <erp-category-goods-list-modal
                    ref="selectGoodsList"
                    :modalWidth="modalWidth"
                    :category="1"
                    @goodsOk="goodsOk"
                    checkval="checkbox"
                  >
                  </erp-category-goods-list-modal>
                  <!--                  </a-col>
                                    <a-col :span="24">-->
                  <!-- 表格 -->
                  <a-table
                    class="mytable"
                    bordered
                    :scroll="{ x: 650, y: 'calc(100vh-350px)' }"
                    :data-source="model.erpGoodsPackageList"
                    :columns="goodsColumns"
                    :rowKey="(record) => record.rowKey"
                    :selected="onSelectChange"
                    :row-selection="{ type: type, selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                    :pagination="false"
                  >
                    <template slot="number" slot-scope="text, record">
                      <edit-number-cell-2
                        :text="text"
                        :disabled="disabled"
                        @change="onCellChange(record, 'number', $event)"
                      ></edit-number-cell-2>
                    </template>
                    <template slot="isProduction" slot-scope="text, record">
                      <a-select
                        :disabled="disabled"
                        :value="text"
                        @change="onCellChange(record, 'isProduction', $event)"
                      >
                        <a-select-option
                          v-for="item in openDictOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </template>
                    <template slot="mainQuantity" slot-scope="text, record">
                      <edit-number-cell-2
                        :text="text"
                        :disabled="disabled"
                        @change="onMainQuantityCellChange(record, 'mainQuantity', $event)"
                      ></edit-number-cell-2>
                    </template>
                    <template slot="meUnit" slot-scope="text">
                      <span>{{ unitDictOptions[text] }}</span>
                    </template>
                    <template slot="auUnit" slot-scope="text">
                      <span>{{ zlunitDictOptions[text] }}</span>
                    </template>
                    <template slot="operation" slot-scope="text, record">
                      <a-popconfirm  title="确认删除?" @confirm="() => onDelete(record.goodsId)">
                        <a  href="javascript:;"> 删除 </a>
                      </a-popconfirm>
                    </template>
                  </a-table>
                  <!--                  </a-col>-->
                </a-card>
              </a-col>
              <a-col :span="14" title="配方信息">
                <a-card class="mycard">

                  <a-row :gutter="10">
                    <a-col :span="4">
                      <h4>配方信息</h4>
                    </a-col>
                    <a-col :span="3">
                      <a-button
                        :disabled="formDisabled || formularConDisabled"
                        type="primary"
                        icon=""
                        size="small"
                        @click="conFormular"
                      >选择配方</a-button>
                      <erp-goods-formular-con-modal @formularOk="formularOk" ref="formularCon" />
                    </a-col>
                    <a-col :span="3">
                      <a-button
                        type="primary"
                        icon=""
                        size="small"
                        @click="handleExprot"
                      >导出</a-button>
                    </a-col>
                    <!--                    <a-col :span="3">
                                          <a-button
                                            :disabled="formDisabled && formularConDisabled"
                                            type="primary"
                                            icon=""
                                            size="small"
                                            @click="addFormular"
                                          >新增配方</a-button>

                                          <ips-tsl-formula-list-modal ref="modalFormular" @ok=""/>

                                        </a-col>-->
                  </a-row>
                  <a-row :span="24">
                    <!--              <a-col :span="3">
                                    <a-form-model-item label="是否保密" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSecrecy">
                                      <j-dict-select-tag
                                        type="list"
                                        :disabled="formDisabled"
                                        v-model="model.isSecrecy"
                                        dictCode="yes_no"
                                        placeholder="请输入是否保密"
                                      />
                                    </a-form-model-item>
                                  </a-col>-->
                    <a-col :span="8">
                      <a-form-model-item label="损耗率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lossRate">
                        <a-input-number
                          v-model="selectedRows[0].lossRate"
                          placeholder="请输入损耗率(%)"
                          style="width: 100%"
                          :disabled="formDisabled || formularConDisabled || formularEditDisabled"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                      <a-form-model-item
                        label="视比重/粘度"
                        :labelCol="{xs: { span: 24 },sm: { span: 10 }}"
                        :wrapperCol="{xs: { span: 24 },sm: { span: 12 }}"
                        prop="proportion"
                      >
                        <a-input-number
                          v-model="selectedRows[0].proportions"
                          :disabled="formDisabled || formularConDisabled || formularEditDisabled"
                          placeholder="(中间值/目标值)"
                          style="width: 100%"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                      <a-form-model-item label="增加费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isIncrease">
                        <j-dict-select-tag
                          type="list"
                          :disabled="formDisabled || formularEditDisabled"
                          v-model="selectedRows[0].isIncrease"
                          dictCode="yes_no"
                          placeholder="请选择是否增加费用"
                        />
                      </a-form-model-item>
                      <a-form-model-item v-show="false" prop="taxPriceCheck">
                        <a-input v-model="taxPriceDummy" />
                      </a-form-model-item>
                    </a-col>
                  </a-row>


                  <a-table
                    ref="formularTable"
                    class="mytable"
                    bordered
                    :data-source="formularDetailList"
                    tableLayout="fixed"
                    :columns="materialColumns"
                    :rowKey="(record) => record.rowNo"
                    :scroll="{ x: 650, y: 'calc(100vh-350px)' }"
                    :pagination="false"
                  >
                    <template slot="formularRatio" slot-scope="text, record">
                      <!--                      <edit-number-cell-2-->
                      <!--                        :disabled="formDisabled && formularConDisabled && formularEditDisabled"-->
                      <!--                        :text="text"-->
                      <!--                        @change="onFormularCellChange(record, 'formula', text)"-->
                      <!--                      />-->

                      <a-input-number :disabled="formDisabled || formularConDisabled || formularEditDisabled" v-model="text" @change="onFormularCellChange(record, 'formula', text)" style="width: 100%" />
                    </template>
                    <template slot="taxPrice" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled ||supplyDisabled"
                        :text="text"
                        @change="onFormularCellChange(record, 'taxPrice', $event)"
                      />
                    </template>

                    <template slot="isSelfProvided" slot-scope="text, record">
                      <!--                      <editoption-cell-->
                      <!--                        :disabled="formDisabled && purchaseDisabled"-->
                      <!--                        :options="options"-->
                      <!--                        :text="text"-->
                      <!--                        @change="onFormularCellChange(record, 'isSelfProvided', $event)"-->
                      <!--                      />-->

                      <a-select
                        :disabled="formDisabled || formularConDisabled || formularEditDisabled"
                        :value="text"
                        @change="onFormularCellChange(record, 'isSelfProvided', $event)"
                      >
                        <a-select-option
                          v-for="item in openDictOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>

                    </template>

                    <!--                    <template slot="actualQuantity" slot-scope="text, record">
                                          <div>
                                            {{ record.formulaProportion * 1000 }}
                                          </div>
                                        </template>-->

                    <template slot="price" slot-scope="text, record">
                      <div>
                        {{ text }}
                      </div>
                    </template>

                  </a-table>
                  <a-row :span="24" v-if="formularDetailList.length>0">

                    <a-col :span="8">
                      <a-form-model-item   label="配方合计" :labelCol="labelCol" :wrapperCol="wrapperCol">

                        {{ Number(formularDetailList.reduce((acc, cur) => acc + Number(cur.formulaProportion),0)).toFixed(2) }}
                      </a-form-model-item>
                    </a-col>

                    <a-col :span="8" >
                      <a-form-model-item label="金额合计" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                        {{ Number(formularDetailList.reduce((acc, cur) => acc + Number(cur.price),0)).toFixed(2) }}

                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
            </a-row>
            <a-row :gutter="8" style="margin: 4px">
              <a-col :span="24" title="包材信息">
                <a-card class="mycard">
                  <a-row :gutter="10">
                    <a-col :span="2">
                      <h4>包材信息</h4>
                    </a-col>
                    <a-col :span="1">
                      <a-button :disabled="this.disabled" type="primary" icon="" size="small" @click="addPackage"> 新增包材 </a-button>
                      <erp-category-goods-list-modal
                        ref="selectPackageList"
                        :modalWidth="modalWidth"
                        :category="2"
                        @packageOk="packageOk"
                        checkval="checkbox"
                      >
                      </erp-category-goods-list-modal>
                    </a-col>
                  </a-row>
                  <a-col :span="24">
                    <j-vxe-table
                      keep-source
                      bordered
                      :ref="refKeys[1]"
                      :dataSource="model.packageList"
                      :columns="packageColumns"
                      :disabled="disabled"
                      class="bold-border"
                    >
                      <template v-slot:isBrought="{ row }">

                        <j-dict-select-tag :disabled="disabled" v-model="row.isBrought" @change="packagMaterials" dictCode="yn"/>
                      </template>

                      <template v-slot:packageInOutType="{ row }">

                        <j-dict-select-tag :disabled="disabled" v-model="row.packageInOutType" @change="packagMaterials" dictCode="package_type" :getPopupContainer="getContainer"/>
                      </template>

                      <template v-slot:proportion="{ row }">

                        <a-input-number :disabled="disabled" style="width:100%" v-model="row.proportion" @change="packagMaterials" :default-value="0" />
                      </template>

                      <template v-slot:action="{ row }">
                        <a  @click="handlePreviewFile(row)">查看版样</a>
                        <a-divider  type="vertical" />
                        <a-popconfirm title="确认删除?" @confirm="() => onDeleteBC(row)">
                          <a href="javascript:;">删除</a>
                        </a-popconfirm>
                      </template>
                    </j-vxe-table>
                  </a-col>
                </a-card>
              </a-col>
            </a-row>
            <a-row :gutter="8" style="margin: 4px">
              <a-col :span="24">
                <a-card class="mycard">
                  <a-row :span="24">
                    <a-col :span="12">
                      <a-form-model-item
                        label="配方要求"
                        :labelCol="labelCol2"
                        :wrapperCol="wrapperCol2"
                        prop="formulaReq"
                      >
                        <a-textarea
                          v-model="model.bussContractReviewDesRequire.formulaReq"
                          :rows="5"
                          allow-clear
                          showCount
                          :disabled="disabled"
                          class="disabled-textarea"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-model-item
                        label="包装要求"
                        :labelCol="labelCol2"
                        :wrapperCol="wrapperCol2"
                        prop="packReq"
                      >
                        <a-textarea
                          v-model="model.bussContractReviewDesRequire.packReq"
                          :rows="5"
                          allow-clear
                          showCount
                          :disabled="disabled"
                          class="disabled-textarea"
                        />
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-card>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>
      <a-tab-pane tab="出口业务报价单" key="3" forceRender>
        <!--        <buss-out-let-quote-form
                  @my-event="getMyEvent"
                  ref="outletquote"
                  :dataId="model.id"
                  :disabled="formDisabled"
                  :currency="model.currency"
                ></buss-out-let-quote-form>-->
        <j-form-container>
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail" layout="horizontal">
            <a-row :span="24">
              <a-card class="mycard">
                <a-col :span="24">
                  <a-row :gutter="10">
                    <a-col :span="1">
                      <h4>包装材料</h4>
                    </a-col>
                  </a-row>
                </a-col>
                <a-col :span="24">
                  <a-table
                    bordered
                    class="mytable"
                    :scroll="{ x: 650, y: 'calc(100vh-350px)' }"
                    :data-source="model.bussOutletQuotePackageList"
                    :columns="warpColumns"
                    :disabled="formDisabled||packageDisabled"
                    :pagination="false"
                  >
                    <template slot="number" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'number', $event)"
                      />
                    </template>
                    <template slot="grams" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'grams', $event)"
                      />
                    </template>
                    <template slot="otherPackageCost" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'other', $event)"
                      />
                    </template>
                    <template slot="packageNumber1" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'packageNumber1', $event)"
                      />
                    </template>
                    <template slot="packageUnitPrice1" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'packageUnitPrice1', $event)"
                      />
                    </template>
                    <template slot="packageNumber2" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'packageNumber2', $event)"
                      />
                    </template>
                    <template slot="packageUnitPrice2" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="Number(text).toFixed(4)"
                        @change="onBussOutletQuoteChange(record, 'packageUnitPrice2', $event)"
                      />
                    </template>
                    <template slot="innerPackageNumber" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'innerPackageNumber', $event)"
                      />
                    </template>
                    <template slot="innerPackageUnitPrice" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||packageDisabled"
                        :text="text"
                        @change="onBussOutletQuoteChange(record, 'innerPackageUnitPrice', $event)"
                      />
                    </template>

                  </a-table>
                </a-col>
              </a-card>
            </a-row>

            <a-row :span="24" style="margin-top:5%">
              <a-card class="mycard">
                <a-col :span="24">
                  <!--            <a-button type="primary" icon="" size="small"> 产品报价 </a-button>-->
                  <a-row :gutter="10">
                    <a-col :span="1">
                      <h4>产品报价</h4>
                    </a-col>
                  </a-row>
                </a-col>
                <a-col :span="24">
                  <a-table
                    bordered
                    class="mytable"
                    :data-source="model.bussOutletQuoteProductList"
                    :columns="productColumns"
                    :scroll="{ x: 650, y: 'calc(100vh-350px)' }"
                    :disabled="formDisabled"
                    :pagination="false"
                  >

                    <template slot="codingFee" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'codingFee', $event)"
                      />
                    </template>

                    <template slot="midExpenses" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'midExpenses', $event)"
                      />
                    </template>

                    <template slot="landFreight" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'landFreight', $event)"
                      />
                    </template>

                    <template slot="seaFreight" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'seaFreight', $event)"
                      />
                    </template>

                    <template slot="certificate" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'certificate', $event)"
                      />
                    </template>

                    <template slot="royalty" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'royalty', $event)"
                      />
                    </template>

                    <template slot="insurancePremium" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'insurancePremium', $event)"
                      />
                    </template>

                    <template slot="commission" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'commission', $event)"
                      />
                    </template>

                    <template slot="other2" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'other2', $event)"
                      />
                    </template>

                    <template slot="ywDamageTon" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'ywDamageTon', $event)"
                      />
                    </template>

                    <template slot="ywTonPrice" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="disabled"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'ywTonPrice', $event)"
                      />
                    </template>

                    <template slot="ywPiecePrice" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="disabled"
                        :text="text"
                        @change="changeYwPiecePrice(record, 'ywPiecePrice', $event)"
                      />
                    </template>

                    <template slot="ywActualQuote" slot-scope="text, record">
                      <edit-number-cell-2
                        :disabled="formDisabled||marketingDisable"
                        :text="text"
                        @change="onBussOutletQuoteProductChange(record, 'ywActualQuote', $event)"
                      />
                    </template>


                    <template slot="ywisCompliantPolicies" slot-scope="text, record">
                      <a-select
                        :disabled="formDisabled||marketingDisable"
                        :value="text"
                        @change="onBussOutletQuoteProductChange(record, 'ywisCompliantPolicies', $event)"
                      >
                        <a-select-option
                          v-for="item in openDictOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>

                    </template>

                  </a-table>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item label="总金额" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="totalPrice">
                    <a-input v-model="model.totalPrice" disabled></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item label="汇率" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="exchangeRate">
                    <a-input @input="handleInput"  v-model="model.exchangeRate" :disabled="formDisabled||marketingDisable"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item label="税率" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="taxRate">
                    <a-input @input="handleInput" v-model="model.taxRate" :disabled="formDisabled||marketingDisable"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-card>

            </a-row>
            <a-row :span="24" style="margin: 4px">
              <a-col :span="12">
                <a-form-model-item label="报价备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="quotationRemarks">
                  <a-textarea
                    v-model="model.quoteRemark"
                    placeholder=""
                    :rows="4"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="财务备录" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="financialRemarks">
                  <a-textarea
                    v-model="model.financeRemark"
                    placeholder=""
                    :rows="4"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>
      <a-tab-pane tab="修改记录" :key="4" :forceRender="true">
        <a-card :bordered="false">
          <tsl-history  :dataId="model.id"></tsl-history>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    <goods-formula-modal ref="selectFormulaList" :modalWidth="modalWidth" @goodsOk="formulasOk"> </goods-formula-modal>
    <!-- <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-button @click="submitForm" type="primary" :loading="confirmLoading">提交</a-button>
    </div> -->
  </a-spin>
</template>

<script>
import { httpAction, getAction, postAction, deleteAction, getFileAccessHttpUrl } from '@/api/manage'
import { validateDuplicateValue, randomUUID } from '@/utils/util'
import ErpCategoryGoodsListModal from '@comp/base/modal/ErpCategoryGoodsListModal'
import EditableCell2 from '@comp/table/EditableCell2'
import EditoptionCell from '@comp/table/EditoptionCell'
import BussOutLetQuoteForm from '../modules/BussOutLetQuoteForm'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import GoodsFormulaModal from './GoodsFormulaModal'
import { Base64 } from 'js-base64'
import store from '@/store'
import TslHistory from './TslHistory.vue'
import moment from 'dayjs'
import { FilePreview } from '@/utils/tslCommon'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import EditNumberCell2 from '../../../../components/table/EditNumberCell2.vue'
import ErpGoodsFormularConModal from './ErpGoodsFormularConModal.vue'
import IpsTslFormulaListModal from '@views/business/ipstslformulalist/modules/IpsTslFormulaListModal'
import {getRefPromise} from "@comp/jeecg/JVxeTable/utils/vxeUtils";
import { axios } from '@/utils/request'
import TslSelectCustomer from '@comp/tsl/modules/TslSelectCustomer.vue'
import Vue from 'vue'

export default {
  name: 'BussContractRequirementReviewForm',
  mixins: [JVxeTableModelMixin],
  components: {
    TslSelectCustomer,
    TslHistory,
    ErpCategoryGoodsListModal,
    EditableCell2,
    BussOutLetQuoteForm,
    EditNumberCell2,
    GoodsFormulaModal,
    ErpGoodsFormularConModal,
    EditoptionCell,
    IpsTslFormulaListModal
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: true,
      required: false,
    },
    /*流程自定义表单数据*/
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      flag:0,
      price:7.25,
      disableSubmit: true,
      supplyDisabled: true, //供应部
      starterDisabled: true, //业务员最后修改
      productDisabled: true, //修改产品信息
      formularConDisabled: true, //配方关联
      formularEditDisabled: true, //配方修改
      qualityCheckDisabled: true, //质量
      packageDisabled: true, //包材报价
      purchaseDisabled: true, //采购确认原料单价
      financeDisabled: true, //财务可修改报价，确认是否符合销售政策
      marketingDisable: true,
      tax: 1.13,
      isAdd: false,
      packageTypeOptions: [],
      showPatternFlag: false,
      isTotalAmountOk: false,
      // 合同评审说明关联文件
      bussContractReviewDesFilesTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token: true,
            responseName: 'message',

            placeholder: '请选择文件',
            defaultValue: '',
          },
          {
            title: '附件说明',
            key: 'fileDesc',
            type: JVXETypes.input,

            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      refKeys: ['bussContractReviewDesFiles', 'goodsPackageList'],
      procSelectRows: [],
      formularDetailList: [],
      //存储用作修改是否生产时获取对应数据
      erpPackageListTmp: [],
      contract: {},
      activeKey: '1',
      modalWidth: 1250,
      category: '',
      goodsId: '',
      packageId: '',
      materialId: '',
      selectedProduct: {},
      model: {
        taxRate:0,
        exchangeRate:0,
        currency:1,
        bussMaterialPriceId:null,
        id: '',
        desId: '',
        erpGoodsPackageList: [],
        reviewGoodsFomularList: [],
        bussOutletQuotePackageList:[],
        bussOutletQuoteProductList:[],
        packageList: [],
        contractCode: '',
        customerId: '',
        customer: '',
        weight: '',
        weightUnit: '',
        payMethod: '',
        deliveryTime: '',
        contractTime: '',
        formulaReq: '',
        packReq: '',
        technology: '', // 原始文本值
        technologyHtml: '',// 用于显示的HTML
        bussContractReviewDesRequire:{

        },
        supply : '',
        supplyHtml : '',
        quality : '',
        qualityHtml : '',
        produce : '',
        produceHtml : '',
        packagingPrice : '',
        packagingPriceHtml : '',
        finance : '',
        financeHtml : '',
        marketing : '',
        marketingHtml : '',
        conclusion : '',
        conclusionHtml : '',
        priceType:'0',
      },
      tabs: {
        activeKey: 1,
      },
      selectedRowKeys: [],
      type: 'radio',
      // 选中行
      selectedRows: [
        {
          lossRate:'',
          proportions:'',
          isIncrease:'0'
        }
      ],
      warpColumns:[
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料名称',
          dataIndex: 'name',
          width: 150,
        },
        {
          title: '规格型号',
          dataIndex: 'spec',
          // width: 100,
        },
        {
          title: '件/吨',
          dataIndex: 'ton',
          // width: 100,
        },
        {
          title: '规格',
          // width:202,
          children: [
            {
              title: '克数',
              dataIndex: 'grams',
              scopedSlots: { customRender: 'grams' },
              // width: 100,
            },
            {
              title: '个数',
              dataIndex: 'number',
              scopedSlots: { customRender: 'number' },
              // width: 100,
            },
          ],
        },
        {
          title: '外包装1',
          // width:310,
          children: [
            // {
            //   title: '面积',
            //   dataIndex: 'packageArea1',
            //   scopedSlots: { customRender: 'packageArea1' },
            //   width: 100,
            // },
            {
              title: '个数',
              dataIndex: 'packageNumber1',
              scopedSlots: { customRender: 'packageNumber1' },
              // width: 100,
            },
            {
              title: '单价',
              dataIndex: 'packageUnitPrice1',
              scopedSlots: { customRender: 'packageUnitPrice1' },
              // width: 100,
            },
            {
              title: '金额',
              dataIndex: 'packageAmount1',
              // width: 100,
            },
          ],
        },
        {
          title: '外包装2',
          // width:310,
          children: [
            // {
            //   title: '面积',
            //   dataIndex: 'packageArea2',
            //   scopedSlots: { customRender: 'packageArea2' },
            //   width: 100,
            // },
            {
              title: '个数',
              dataIndex: 'packageNumber2',
              scopedSlots: { customRender: 'packageNumber2' },
              // width: 100,
            },
            {
              title: '单价',
              dataIndex: 'packageUnitPrice2',
              scopedSlots: { customRender: 'packageUnitPrice2' },
              // width: 100,
            },
            {
              title: '金额',
              dataIndex: 'packageAmount2',
              // width: 100,
            },
          ],
        },
        {
          title: '内包装',
          // width:310,
          children: [
            // {
            //   title: '面积',
            //   dataIndex: 'innerPackageArea',
            //   scopedSlots: { customRender: 'innerPackageArea' },
            //   width: 100,
            // },
            {
              title: '个数',
              dataIndex: 'innerPackageNumber',
              scopedSlots: { customRender: 'innerPackageNumber' },
              // width: 100,
            },
            {
              title: '单价',
              dataIndex: 'innerPackageUnitPrice',
              scopedSlots: { customRender: 'innerPackageUnitPrice' },
              // width: 100,
            },
            {
              title: '金额',
              dataIndex: 'innerPackageAmount',
              // width: 100,
            },
          ],
        },
        {
          title: '其他',
          dataIndex: 'other',
          scopedSlots: { customRender: 'otherPackageCost' },
          // width: 100,
        },
        {
          title: '合包装成本',
          dataIndex: 'packageCost',
          // width: 100,
        },
        /*        {
                  title: '操作',
                  width: 80,
                  dataIndex: 'operation',
                  scopedSlots: { customRender: 'operation' },
                },*/
      ],
      productColumns:[
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          fixed: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料名称',
          dataIndex: 'name',
          width: 150,
          fixed: 'left',
        },
        {
          title: '规格型号',
          dataIndex: 'spec',
          fixed: 'left',
          width: 100,
        },
        {
          title: '包装规格',
          dataIndex: 'packageSpec',
          width: 100,
        },
        {
          title: '包装方式',
          dataIndex: 'packageMethod',
          width: 100,
        },
        {
          title: '打码费',
          dataIndex: 'codingFee',
          width: 100,
          scopedSlots: { customRender: 'codingFee' },
        },
        {
          title: '件/吨',
          dataIndex: 'ton',
          width: 100,
        },
        {
          title: '原料',
          dataIndex: 'material',
          width: 100,
        },
        {
          title: '包材',
          dataIndex: 'packageMaterials',
          width: 100,
        },
        {
          title: '中间费用',
          dataIndex: 'midExpenses',
          scopedSlots: { customRender: 'midExpenses' },
          width: 100,
        },
        {
          title: '合计',
          dataIndex: 'total',
          width: 100,
        },
        {
          title: '出厂价',
          children: [
            {
              title: '/7.25',
              width: 100,
              dataIndex: 'exWorksPrice',
            },
          ],
        },
        {
          title: '陆运费',
          dataIndex: 'landFreight',
          scopedSlots: { customRender: 'landFreight' },
          width: 100,
        },
        {
          title: '海运费',
          dataIndex: 'seaFreight',
          scopedSlots: { customRender: 'seaFreight' },
          width: 100,
        },
        {
          title: '证书费用',
          dataIndex: 'certificate',
          scopedSlots: { customRender: 'certificate' },
          width: 100,
        },
        {
          title: '版费',
          dataIndex: 'royalty',
          scopedSlots: { customRender: 'royalty' },
          width: 100,
        },
        {
          title: '保费',
          dataIndex: 'insurancePremium',
          scopedSlots: { customRender: 'insurancePremium' },
          width: 100,
        },
        {
          title: '佣金',
          dataIndex: 'commission',
          scopedSlots: { customRender: 'commission' },
          width: 100,
        },
        {
          title: '其他',
          dataIndex: 'other2',
          scopedSlots: { customRender: 'other2' },
          width: 100,
        },
        {
          title: '合计',
          dataIndex: 'total2',
          width: 100,
        },
        {
          title: '出厂价',
          children: [
            {
              title: '数量(吨)',
              width: 100,
              dataIndex: 'ywTon',
            },
            {
              title: '赔偿数量(吨)',
              width: 100,
              dataIndex: 'ywDamageTon',
              scopedSlots: { customRender: 'ywDamageTon' },
            },
            {
              title: '吨价',
              width: 100,
              dataIndex: 'ywTonPrice',
              scopedSlots: { customRender: 'ywTonPrice' },
            },
            {
              title: '件价',
              width: 100,
              dataIndex: 'ywPiecePrice',
              scopedSlots: { customRender: 'ywPiecePrice' },
            },
            {
              title: '实际报价',
              width: 100,
              dataIndex: 'ywActualQuote',
              scopedSlots: { customRender: 'ywActualQuote' },
            },
            {
              title: '是否符合政策',
              width: 100,
              dataIndex: 'ywisCompliantPolicies',
              scopedSlots: { customRender: 'ywisCompliantPolicies' },
            },
          ],
        },
      ],
      goodsColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 30,
          align: 'center',
          fixed: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '客户物料编号',
          dataIndex: 'customCode',
          fixed: 'left',
          width: 90,
        },
        {
          title: '物料编码',
          dataIndex: 'packageCode',
          fixed: 'left',
          width: 70,
        },
        {
          title: '物料名称',
          dataIndex: 'packageName',
          fixed: 'left',
          width: 90,
        },
        {
          title: '规格型号',
          dataIndex: 'noneSpec',
          width: 100,
        },
        {
          title: '配方序号',
          dataIndex: 'number',
          scopedSlots: { customRender: 'number' },
          width: 80,
        },
        {
          title: '是否生产',
          dataIndex: 'isProduction',
          scopedSlots: { customRender: 'isProduction' },
          width: 60,
        },
        {
          title: '包装方式',
          dataIndex: 'packageType',
          width: 80,
        },
        {
          title: '主数量',
          dataIndex: 'mainQuantity',
          scopedSlots: { customRender: 'mainQuantity' },
          width: 80,
        },
        {
          title: '主单位',
          dataIndex: 'meUnit',
          width: 50,
          scopedSlots: { customRender: 'meUnit' },
        },
        {
          title: '辅数量',
          dataIndex: 'auxiliaryQuantity',
          width: 80,
        },
        {
          title: '辅单位',
          dataIndex: 'auUnit',
          width: 50,
          scopedSlots: { customRender: 'auUnit' },
        },
        {
          title: '配方年',
          dataIndex: 'formulaYear',
          width: 40,
        },
        {
          title: '配方编码',
          dataIndex: 'formulaCode',
          width: 70,
        },
        {
          title: '配方号',
          dataIndex: 'formulaNumber',
          width: 70,
        },
        {
          title: '配方名称',
          dataIndex: 'formulaDefine',
          width: 70,
        },
        {
          title: '库存',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 80,
          // fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      materialColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 40,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料编码',
          dataIndex: 'materialCode',
          width: 120,

        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: 120,

        },
        {
          title: '规格型号',
          dataIndex: 'materialSpec',
          width: 120,
        },
        {
          title: '是否自带',

          dataIndex: 'isSelfProvided',
          scopedSlots: { customRender: 'isSelfProvided' },
          width: 60,
        },
        {
          title: '配方%',
          dataIndex: 'formulaProportion',
          scopedSlots: { customRender: 'formularRatio' },
          width: 60,
        },
        {
          title: '数量',
          dataIndex: 'actualQuantity',
          width: 80,
        },
        {
          title: '含税单价',
          dataIndex: 'taxPrice',
          width: 80,
          scopedSlots: { customRender: 'taxPrice' },
        },
        {
          title: '不含税单价',
          dataIndex: 'noTaxPrice',
          width: 90,
        },
        {
          title: '金额',
          dataIndex: 'price',
          scopedSlots: { customRender: 'price' },
          // width: 100,

        },
      ],

      packageColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料编号',
          dataIndex: 'packageCode',
          key: 'packageCode',
        },
        {
          title: '物料名称',
          dataIndex: 'packageName',
          key: 'packageName',
        },
        {
          title: '规格型号',
          dataIndex: 'noneSpec',
          key: 'noneSpec',
        },
        {
          title: '是否自带',
          dataIndex: 'isBrought',
          key: 'isBrought',
          type: JVXETypes.slot,
          slotName:'isBrought',
          /*          type: JVXETypes.select,
                    options: [
                      // 下拉选项
                      { title: '是', value: '1' },
                      { title: '否', value: '0' },
                    ],*/
        },
        {
          title: '包材类别',
          dataIndex: 'packageInOutType',
          key: 'packageInOutType',
          type: JVXETypes.slot,
          slotName:'packageInOutType',
          // type: JVXETypes.select,
          // dictCode: 'package_type',
        },
        {
          title: '比例数量',
          dataIndex: 'proportion',
          // type: JVXETypes.input,
          type: JVXETypes.slot,
          slotName:'proportion',
          key: 'proportion',
        },
        {
          title: '损耗率(%)',
          dataIndex: 'lossRate',
          key: 'lossRate',
          type: JVXETypes.input,
        },
        {
          title: '材质',
          dataIndex: 'materialQuality',
          key: 'materialQuality',
        },
        {
          title: '尺寸',
          dataIndex: 'size',
          key: 'size',
        },
        {
          title: '包装要求',
          dataIndex: 'requirements',
          key: 'requirements',
          type: JVXETypes.input,
        },
        /*     {
               title: '版样',
               dataIndex: 'patternFile',
               key: 'patternFile',
               type: JVXETypes.file,
               token: true,
             },*/
        {
          title: '操作',
          key: 'action',
          type: JVXETypes.slot,
          fixed: 'right',
          minWidth: '100px',
          align: 'center',
          slotName: 'action',
        },
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 28%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 4 },
        // style: 'width: 15%;',
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      labelCol24: {
        xs: { span: 24 },
        sm: { span: 24 },
        style: 'width: 100%;',
      },
      wrapperCol24: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      confirmLoading: false,
      validatorRules: {
        code: [{ required: true, message: '请输入评审表编号!' }],
        currency: [{ required: true, message: '请选择币种!' }],
        flowFlag: [{ required: true, message: '请选择审批流程!' }],
        /*bussMaterialPriceId: [{ required: true, message: '请选择价格执行表!' }],*/
        priceType:[{required: true , message:'请选择单价类型'}]
        // schedulingNumber: [
        //   { required: true, message: '请填写销售订单号！（如果是补单，请填写销售订单号；如果是新单，请填写无）!' },
        // ],
      },
      url: {
        price:'/procurement/materialPriceApproval/list',
        add: '/review/bussContractRequirementReview/add',
        edit: '/review/bussContractRequirementReview/edit',
        queryById: '/review/bussContractRequirementReview/queryById',
        productByReviewId: '/review/bussContractRequirementReview/reviewProduct/ByReviewId',
        productByIds: '/review/bussContractRequirementReview/reviewProduct/ids',
        packageByIds: '/review/bussContractRequirementReview/reviewPackage/ids',
        bussContractReviewDesFiles: {
          list: '/business/bussContractReviewDes/queryBussContractReviewDesFilesByMainId',
        },
        bussContractReviewDesRequireFiles: {
          list: '/review/bussContractReviewDesRequireFiles/queryBussContractReviewDesRequireFilesByMainId',
        },
        contractReviewPatterns: {
          list: '/contract.pattern/tslContractReviewPattern/list',
          add: '/contract.pattern/tslContractReviewPattern/add',
          edit: '/contract.pattern/tslContractReviewPattern/edit',
          delete: '/contract.pattern/tslContractReviewPattern/delete',
          model: '/pattern/erpGoodsPattern/detail',
        },
        queryFormularDetailList: '/ipstslformulalist/ipsTslFormulaList/queryFormulaMaterialPriceByMainId',
        getFormulaResult:'/ipstslformulalist/ipsTslFormulaList/getFormulaResult'
      },
      openDictOptions: {},
      unitDictOptions: {},
      zlunitDictOptions: {},
      patternDictOptions: {},
      dictOptions:[]
    }
  },
  computed: {
    taxPriceDummy() {
      return this.formularDetailList.length ? 'ok' : '';
    },
    formDisabled() {
      if (this.customFormData != null && this.customFormData.id) {
        return false
      }
      return true
    },
  },
  created() {
    console.log('this.customFormData=', this.customFormData)
    if (this.customFormData != null && this.customFormData.id) {
      this.model = this.customFormData
      this.model.packageList=[]
      this.edit(this.customFormData)
    }
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initDictConfig()

    getAction(this.url.price,{pageSize:-1,order:'desc',column: 'createTime',searchModel:4}).then((res) => {
      res.result.records.forEach((item) => {
        this.dictOptions.push({text:item.executeCode,value:item.id})
        // 设置默认值为第一条记录
        if (this.dictOptions.length > 0) {
          this.model.bussMaterialPriceId = this.dictOptions[0].value; // 设置为第一条记录的 ID
        }
      })

    })
    //this.editAfter() //现在子表内容需要
  },
  watch: {
    selectedRows: {
      deep: true,  // 深度监听（适用于对象/数组内部变化）
      immediate: true,  // 立即触发一次
      handler(newRows) {
        const proportions = newRows[0]?.proportions;
        const isIncrease=newRows[0]?.isIncrease;
        console.log('proportion 变化:', proportions,isIncrease);
        this.model.proportion=newRows[0]?.proportions;
        this.model.isIncrease=newRows[0]?.isIncrease;
        console.log("aaaaa",this.selectedRows[0],this.model)
        this.$nextTick(() => this.$refs.formProduct.validate());
        // 在这里执行你的逻辑
      }
    }
  },
  mounted() {
    getAction("/review/bussContractRequirementReview/getPrice",{currency:this.model.currency}).then((res)=>{
      if(res.success){
        this.model.exchangeRate = res.result.exchangeRate
        this.model.taxRate = res.result.taxRate
      }})
    console.log("到到到到到到到到到到到到到到到到到到到到到到到到到到到到到到到",this.model)
    if (this.model.id) {
      /* this.$refs.outletquote.getFormData(this.model.id)
       if (this.model.currency) {
         this.$refs.outletquote.getLimit(this.model.currency)
       }*/
      this.checkTaskDisabled(this.model.taskName)
    }

  },
  methods: {
    handleInput(){
      this.productQuotation()
    },
    reloadPackagePrice(priceId) {
      const packageIds = [];
      this.model.erpGoodsPackageList.forEach(g => {
        (g.packageVos || []).forEach(p => packageIds.push(p.packageId));
      });
      if (!packageIds.length) return Promise.resolve();

      return postAction(this.url.packageByIds, {
        ids: packageIds,
        priceId: priceId
      }).then(res => {
        if (!res.success) return Promise.reject(res.message);

        // 写回最新包材价
        res.result.forEach(newP => {
          this.model.erpGoodsPackageList.forEach(g => {
            (g.packageVos || []).forEach(p => {
              if (p.packageId === newP.packageId && newP.taxPrice != null) {
                p.taxPrice   = newP.taxPrice;
                p.noTaxPrice = newP.noTaxPrice;
              }
            });
          });
        });
      });
    },
    // 统一请求：按新执行表给所有已选配方重新取价
    reloadFormulaPrice(priceId) {
      const goodsIds = this.model.erpGoodsPackageList
        .filter(g => g.formulaId)
        .map(g => g.goodsId);
      if (!goodsIds.length) return Promise.resolve();

      return postAction(this.url.productByIds, {
        ids: goodsIds,
        priceId: priceId
      }).then(res => {
        if (!res.success) return Promise.reject(res.message);

        // 把返回的最新价格写回本地
        res.result.forEach(newGoods => {
          const row = this.model.erpGoodsPackageList.find(r => r.goodsId === newGoods.id);
          if (!row) return;

          // 覆盖配方明细价
          row.formularVos.forEach(f => {
            const newF = (newGoods.formularVos || []).find(nf => nf.materialId === f.materialId);
            if (newF && newF.taxPrice != null) {
              f.taxPrice   = newF.taxPrice;
              f.noTaxPrice = newF.noTaxPrice;
              f.price      = (Number(f.noTaxPrice) * Number(f.actualQuantity)).toFixed(2);
            }
          });
        });
        this.formularDetailList = (this.selectedRows[0] && this.selectedRows[0].formularVos) || [];
      });
    },
    // 材料价格执行表切换 → 全流程重算
    onPriceExecuteChange(newPriceId) {
      if (!newPriceId) return;
      this.$message.info('正在按新执行表重新计价，请稍候...');

      // 1. 先重拉所有配方单价
      this.reloadFormulaPrice(newPriceId).then(() => {
        // 2. 再重拉所有包材单价
        return this.reloadPackagePrice(newPriceId);
      }).then(() => {
        // 3. 最后把出口报价重新算一遍
        this.packagMaterials();      // 包材成本
        this.productQuotation();     // 产品报价
        this.$message.success('价格已按新执行表刷新完成');
      }).catch(err => {
        this.$message.error('刷新失败：' + (err.message || err));
      });
    },
    validateTaxPrice(rule, value, callback) {
      for (let i = 0; i < this.formularDetailList.length; i++) {
        const it = this.formularDetailList[i];
        if (it.taxPrice === null || it.taxPrice === undefined || it.taxPrice === ''&&it.isSelfProvided==0) {
          callback(new Error(`第 ${i + 1} 行“含税单价”不能为空`));
          return;
        }
      }
      callback();
    },
    getContainer() {
      return document.body;
    },
    handleClick(){
      console.log("abc")
      this.$nextTick(()=>{
        this.$refs.selectCustomer.add()
      })
    },
    handleSelect(row){
      console.log("21313",row)
      this.model.bussContractReviewDesRequire.customerId=row[0].id
      Vue.set(this.model.bussContractReviewDesRequire,'customerId_dictText',row[0].name)
      this.changeCustomer()
      console.log("dddd",this.model)
    },
    changeCustomer() {
      getAction('/business/bussContractReviewDes/querySalesman', { id: this.model.bussContractReviewDesRequire.customerId }).then((res) => {
        console.log(res)
        if (res.success) {
          // this.model.salesman = res.result.salesmanId
          // this.model.customer = res.result.category

          Vue.set(this.model.bussContractReviewDesRequire, 'salesman', res.result.salesman)
          Vue.set(this.model.bussContractReviewDesRequire, 'salesmanName', res.result.salesmanName)
          Vue.set(this.model.bussContractReviewDesRequire, 'customer', res.result.category)
          /*          let type = res.result.type
                    if (type && type.name === '国内/OEM') {
                      this.model.desFlowType = 2
                    }
                    if (type && type.name === '国贸') {
                      this.model.desFlowType = 1
                    }*/
        } else {
        }
      })
    },
    handleExprot(){
      console.log("aaaaaaaaaaaaaaaaaaa",this.formularDetailList)
      this.handleExportXls('配方导出')
    },
    handleExportXls(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      axios({
        url: "/review/bussContractRequirementReview/export",
        data: this.formularDetailList,
        method:'post' ,
        responseType: 'blob'
      }).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    handleChangeCustomr(data){
      getAction("/review/bussContractRequirementReview/getSaleManByCustomerId",{customerId:data}).then((res) => {
        if(res.success){
          this.model.bussContractReviewDesRequire.salesman=res.result
        }
      })
    },
    addNew(){
      this.bussContractReviewDesFilesTable.dataSource = []
      this.getPfCode()
      this.getSchedulingNumber()
    },
    complete() {
      /*this.submitForm()*/
    },
    handlePreviewFile(row) {
      console.log(row, '版样文件')
      if (!row.patternFile) {
        return this.$message.error("无版样文件,请到版样管理添加版样")
      }
      FilePreview(row.patternFile)
    },
    formularOk(data) {
      if (data && data.id) {
        /* if(this.model.bussMaterialPriceId===null || this.model.bussMaterialPriceId===""){
           return this.$message.error("请先至第一个页签（合同评审表）选择材料价格执行表")
         }*/
        getAction(this.url.queryFormularDetailList, { id: data.id ,priceId : this.model.bussMaterialPriceId}).then((res) => {
          if (res.success) {
            this.formularDetailList = res.result.map((item) => {
              item.productId = this.selectedProduct.goodsId
              item.reviewId = this.model.id
              item.rowNo = randomUUID()
              item.isIncrease = '0'
              item.actualQuantity = item.actualNumber
              item.price = item.noTaxPrice != null && item.actualNumber != null ? Number(item.noTaxPrice * item.actualNumber).toFixed(2) : 0
              return item
            })
            const dataSource = [...this.model.erpGoodsPackageList]
            const target = dataSource.find((item) => item.goodsId === this.selectedProduct.goodsId)
            target.formulaId = data.id
            target.formulaYear = data.formulaYear
            target.formulaCode = data.formulaCode
            target.formulaDefine = data.formulaDefine
            target.formulaNumber = data.formulaNumber
            target.formularVos = [...this.formularDetailList]
            this.model.erpGoodsPackageList = dataSource
            this.deepCopyGoodsList(this.model.erpGoodsPackageList)
            this.productQuotation()
          }
        })
      }
    },
    conFormular() {
      if (this.selectedRows[0].goodsId==null) {
        this.$message.warning('请先选择产品')
        return
      }

      let good = {
        id: this.selectedProduct.goodsId,
        code: this.selectedProduct.packageCode,
        name: this.selectedProduct.packageName,
      }
      this.$refs.formularCon.add([good])
      this.$refs.formularCon.title = '关联BOM'
      this.$refs.formularCon.disableSubmit = false
    },
    addFormular(){

      this.$refs.modalFormular.add();
      this.$refs.modalFormular.title = "新增配方";
      this.$refs.modalFormular.disableSubmit = false;
    },
    checkTaskDisabled(taskName) {
      console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
      console.log(taskName, 'taskName')
      if (taskName) {
        this.disableSubmit = false
        if (taskName == '张顺欣' || taskName == '关联配方') {
          this.formularConDisabled = false
          this.formularEditDisabled = false
          this.validatorRules = {
            proportion: [{ required: true, message: '请输入视比重!' }],
            isIncrease: [{ required: true, message: '是否增加费用不能为空!' }],
          }
        }  else if (taskName == '质检部' || taskName == '王淑保') {
          this.qualityCheckDisabled = false
        } else if (taskName == '生产部' || taskName == '王吉信' || taskName == '赵勇') {
          this.productDisabled = false
        } else if (taskName == '包材核价' || taskName == '毕翠霞') {
          this.packageDisabled = false
        } else if(taskName== '营销部'){
          this.marketingDisable =false
        }else if (taskName == '业务员最后更改') {
          this.starterDisabled = false
        }else if (taskName == '供应部'){
          this.supplyDisabled = false
          this.validatorRules = {
            taxPriceCheck: [{ validator: this.validateTaxPrice, trigger: 'change' }]
          }
        }else if(taskName == '包材核价供应部'){
          this.packageDisabled = false
          this.supplyDisabled = false
          this.validatorRules = {
            taxPriceCheck: [{ validator: this.validateTaxPrice, trigger: 'change' }]
          }
        }
        this.$refs.outletquote.checkTaskDisabled(taskName)
      }
    },
    changeCurrency(val) {
      console.log(val, '修改币种')
      this.$refs.outletquote.getLimit(this.model.currency)
    },
    handlePreviewReviewDesFiles(row) {
      if (row && row.filePath) {
        FilePreview(row.filePath)
      }
    },
    initDictConfig() {
      initDictOptions('package_type').then((res) => {
        console.log(res)
        if (res.success) {
          console.log(res.result)
          this.packageTypeOptions = res.result
        }
      })
      initDictOptions('yes_no').then((res) => {
        console.log(res)
        if (res.success) {
          console.log(res.result)
          this.openDictOptions = res.result
        }
      })
      //初始化字典 - 主单位
      initDictOptions('ji_unit').then((res) => {
        var unitDictOptions = this.unitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
      //初始化字典 - 辅单位
      initDictOptions('zl_unit').then((res) => {
        var zlunitDictOptions = this.zlunitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            zlunitDictOptions[item.value] = item.label
          })
        }
        this.zlunitDictOptions = zlunitDictOptions
      })
      //初始化字典 --配置项
      initDictOptions('tsl_config').then((res) => {
        if (res.success) {
          console.log(res.result)
          let item = res.result.filter((t) => t['text'] == '原材料税率')
          if (item && item.length > 0) {
            console.log(item, '获取原材料税率：', item[0]['value'])
            this.tax = Number.parseFloat(item[0]['value'])
          }
        }
      })
      //初始化字典 - 是否有版样
      this.patternDictOptions = {
        1: '是',
        0: '否',
      }
    },
    tabsChange(activeKey) {
      this.showPatternFlag = false
      /*      if (this.isAdd) {
              this.activeKey = '1'
              this.tabs.activeKey = 1
              return
            }*/
      this.activeKey = activeKey
      this.tabs.activeKey = activeKey
      console.log("abc",this.model.priceType)
      if (this.model.currency == 1){
        this.productColumns
          .find(c => c.title === '出厂价' && c.children.some(child => child.dataIndex === 'exWorksPrice'))
          .children
          .forEach(col => {
            if (col.dataIndex === 'exWorksPrice')      col.title = '*1.13';
            console.log("col",col)
          });
      }else {
        this.productColumns
          .find(c => c.title === '出厂价' && c.children.some(child => child.dataIndex === 'exWorksPrice'))
          .children
          .forEach(col => {
            if (col.dataIndex === 'exWorksPrice')      col.title = '/7.25';
            console.log("col",col)
          });
      }
      if (this.model.priceType == '0') {
        this.productColumns
          .find(c => c.title === '出厂价' && c.children.some(child => child.dataIndex === 'ywTon'))
          .children
          .forEach(col => {
            if (col.dataIndex === 'ywTon')      col.title = '吨数';
            console.log("col",col)
          });
      }
      if (this.model.priceType == '1') {
        this.productColumns
          .find(c => c.title === '出厂价' && c.children.some(child => child.dataIndex === 'ywTon'))
          .children
          .forEach(col => {
            if (col.dataIndex === 'ywTon')      col.title = '件数';
            console.log("col",col)
          });
      }
    },
    getPfCode() {
      postAction('/sys/fillRule/executeRuleByCode/contract_review_code', {}).then((res) => {
        this.model.code = res.result
        this.$forceUpdate()
      })
    },
    getSchedulingNumber() {
      let autoCodeUrl = '/sys/fillRule/executeRuleByCode/'
      // if (this.model.desFlowType == 2) {
      //   autoCodeUrl += 'sales_order_code_international'
      // } else {
      autoCodeUrl += 'sales_order_code_domestic'
      // }
      postAction(autoCodeUrl, {}).then((res) => {
        this.model.schedulingNumber = res.result
        this.$forceUpdate()
      })
    },
    add(rows) {
      this.contract = rows[0]
      /*var record = {}
      console.log(rows[0], 'rows[0]')*/
      /*      Vue.set(record, 'reviewDescribeId', this.contract.id)
            Vue.set(record, 'code', this.contract.code)
            Vue.set(record, 'customerId', this.contract.customerId)
            Vue.set(record, 'salesman', this.contract.salesman)
            Vue.set(record, 'customer', this.contract.customer)
            Vue.set(record, 'weight', this.contract.weight)
            Vue.set(record, 'weightUnit', this.contract.weightUnit)
            Vue.set(record, 'payMethod', this.contract.payMethod)
            Vue.set(record, 'deliveryTime', this.contract.deliveryTime)
            Vue.set(record, 'contractTime', this.contract.createTime)
            Vue.set(record, 'formulaReq', this.contract.formulaReq)
            Vue.set(record, 'packReq', this.contract.packReq)
            Vue.set(record, 'erpGoodsPackageList', [])
            Vue.set(record, 'reviewGoodsFomularList', [])
            Vue.set(record, 'packageList', [])*/

      Vue.set(this.model, 'flowFlag', 1)
      Vue.set(this.model, 'contractTime', this.contract.createTime)

      //this.model = Object.assign({}, record)
      this.model.bussContractReviewDesRequire = rows[0]
      this.model.bussMaterialPriceId=this.model.bussContractReviewDesRequire.bussMaterialPriceId
      console.log('this.model',this.model )
      this.getPfCode()
      this.bussContractReviewDesFilesTable.dataSource = []
      let params = { id: this.model.bussContractReviewDesRequire.id }
      this.requestSubTableData(this.url.bussContractReviewDesFiles.list, params, this.bussContractReviewDesFilesTable)

      this.getSchedulingNumber()

      this.isAdd = true
    },
    edit(record) {
      console.log("-------------------")
      console.log(record)
      getAction('/review/bussContractReviewDesRequire/queryById', { id: record.desId,reviewId:record.id }).then((res) => {
        let records = res.result
        // if (records != null) {
        /*          Vue.set(record, 'contractCode', records.code)
                  Vue.set(record, 'customerId', records.customerId)
                  Vue.set(record, 'salesman', this.contract.salesman)
                  Vue.set(record, 'customer', records.customer)
                  Vue.set(record, 'weight', records.weight)
                  Vue.set(record, 'weightUnit', records.weightUnit)
                  Vue.set(record, 'payMethod', records.payMethod)
                  Vue.set(record, 'deliveryTime', records.deliveryTime)
                  //Vue.set(record, 'contractTime', records.createTime)
                  Vue.set(record, 'formulaReq', records.formulaReq)
                  Vue.set(record, 'packReq', records.packReq)
                  Vue.set(record, 'erpGoodsPackageList', [])
                  Vue.set(record, 'reviewGoodsFomularList', [])
                  Vue.set(record, 'packageList', [])*/
        this.model = Object.assign({}, record)
        this.model.bussContractReviewDesRequire = records.bussContractReviewDesRequire
        if(this.model.bussContractReviewDesRequire.bussMaterialPriceId!=null){
          this.model.bussMaterialPriceId=this.model.bussContractReviewDesRequire.bussMaterialPriceId
        }
        this.model.bussOutletQuotePackageList = records.bussOutletQuotePackageList
        this.model.bussOutletQuoteProductList = records.bussOutletQuoteProductList
        // }

        //此处可调用出口业务报价单edit，传入出口业务报价单model
        this.visible = true

        this.editAfter()
      })
    },
    editAfter() {
      let _this = this
      console.log(this.model.id, 'modelId', this.model)
      if(this.model.bussContractReviewDesRequire.salesman!=null){
        getAction("/business/bussContractReviewDes/getSalesmanDict",{id:this.model.bussContractReviewDesRequire.salesman}).then(res=>{
          if (res.success) {
            this.model.bussContractReviewDesRequire.salesman_dictText=res.result
          }
        })
      }
      if (this.model.bussContractReviewDesRequire.customerId!=null){
        getAction("/business/bussContractReviewDes/getCustomerIdDict",{id:this.model.bussContractReviewDesRequire.customerId}).then(res=>{
          if (res.success) {
            this.model.bussContractReviewDesRequire.customerId_dictText=res.result
          }
        })
      }
      _this.model.erpGoodsPackageList = []
      getAction(this.url.productByReviewId, { id: this.model.id }).then((res) => {
        let erpGoodsList = res.result
        erpGoodsList.forEach(function (item, index) {
          console.log(item, index, '获取评审表关联物料')
          let detail = {}
          detail.goodsId = item.id
          detail.rowKey = item.id
          detail.customCode = item.customCode
          detail.packageCode = item.code
          detail.packageName = item.name
          detail.coRate = item.coRate
          detail.noneSpec = item.noneSpec
          detail.meUnit = item.meUnit
          detail.auUnit = item.auUnit
          detail.formulaId = item.formulaId
          detail.formulaCode = item.formulaCode
          detail.formulaNumber = item.formulaNumber
          detail.formulaDefine = item.formulaDefine
          detail.formulaYear = item.formulaYear
          detail.packageType = item.packageType
          detail.packageVos = item.packageVos
          detail.isIncrease = item.isIncrease
          detail.lossRate = item.lossRate
          detail.proportions = item.proportions
          detail.quantity = item.quantity

          detail.formularVos = item.formularVos.map((item) => {
            return { ...item, rowNo: item.id, price:item.noTaxPrice!=null&&item.actualQuantity!=null?Number(item.noTaxPrice*item.actualQuantity).toFixed(2):0}
          })

          detail.number = item.number
          detail.mainQuantity = item.mainQuantity
          detail.auxiliaryQuantity = item.auxiliaryQuantity
          detail.isProduction = item.isProduction
          // _this.filterPackageId(item.id);
          _this.model.erpGoodsPackageList.push(detail)
        })


        if (_this.model.erpGoodsPackageList == null||_this.model.erpGoodsPackageList.length==0) {
          _this.model.erpGoodsPackageList = []
          _this.isTotalAmountOk = false
          _this.model.totalProductAmount = 0
        } else {
          _this.checkIsTotalAmountOk()
          _this.deepCopyGoodsList(_this.model.erpGoodsPackageList)
          _this.$nextTick(()=>{
            _this.selectedRowKeys = _this.model.erpGoodsPackageList.map((item) => item.rowKey)?.slice(0,1)??[]
          })
          if(_this.selectedRowKeys){
            _this.onSelectChange(_this.selectedRowKeys, _this.model.erpGoodsPackageList)
          }

        }
        this.productQuotation()
      })

      this.bussContractReviewDesFilesTable.dataSource = []
      let params = { id: this.model.bussContractReviewDesRequire.id }
      this.requestSubTableData(this.url.bussContractReviewDesRequireFiles.list, params, this.bussContractReviewDesFilesTable)

      console.log("++++++++++++++1111111111++++++++++++")
      // 加载流程记录并拼接到表单字段
      this.loadFlowRecords()
    },

// 加载流程记录并拼接到表单字段
    loadFlowRecords() {
      if (!this.model || !this.model.id) {
        return
      }
      console.log("++++++++++++++222222222222222222222++++++++++++")

      getAction('/flowable/task/flowRecordBydataid', { dataId: this.model.id })
        .then(res => {
          if (res.success && res.result && res.result.flowList && res.result.flowList.length > 0) {
            const flowRecordsList = res.result.flowList.slice().reverse()
            console.log("++++++++++++++33333333333333333++++++++++++")
            console.log(flowRecordsList)
            // 初始化表单字段
            this.model.technologyHtml = '';
            this.model.technology = ''
            this.model.supply = ''
            this.model.supplyHtml = ''
            this.model.quality = ''
            this.model.qualityHtml = ''
            this.model.produce = ''
            this.model.produceHtml = ''
            this.model.packagingPrice = ''
            this.model.packagingPriceHtml = ''
            this.model.finance = ''
            this.model.financeHtml = ''
            this.model.marketing = ''
            this.model.marketingHtml = ''
            this.model.conclusion = ''
            this.model.conclusionHtml = ''
            // 技术部：technology
            // 供应部：supply
            // 质检部：quality
            // 生产部：produce
            // 包材核价：packagingPrice
            // 财务部：finance
            // 营销部：marketing
            // 评定结论：conclusion
            // 遍历流程记录，拼接到对应字段
            flowRecordsList.forEach((record, index) => {
              // 拼接A1和A2到a字段
              if (record.taskName === "技术部") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.technologyHtml = htmlContent;
              }

              // 拼接A1和A2到a字段
              if (record.taskName === "质检部") {
                const comment = record.listFlowCommentDto[0].comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.qualityHtml = htmlContent;
              }
              // 拼接A1和A2到a字段
              if (record.taskName === "供应部") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.supplyHtml = htmlContent;
              }
              // 拼接A1和A2到a字段
              if (record.taskName === "生产部") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.produceHtml = htmlContent;
              }
              // 拼接A1和A2到a字段
              if (record.taskName === "包材核价") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.packagingPriceHtml = htmlContent;
              }
              // 拼接A1和A2到a字段
              if (record.taskName === "财务部") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.financeHtml = htmlContent;
              }
              // 拼接A1和A2到a字段
              if (record.taskName === "营销部") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.marketingHtml = htmlContent;
              }
              // 拼接A1和A2到a字段
              if (record.taskName === "营销总监") {
                const comment = record.listFlowCommentDto?.[0]?.comment || '';
                const assigneeName = record.assigneeName || '';
                const timeStr = record.finishTime || record.createTime || '';

                // 构建HTML内容
                const htmlContent = `
                <div class="record-item" style="margin-bottom: 15px; border: 0px solid #e8e8e8; padding: 10px; border-radius: 4px;">
                  <div style="display: flex; flex-direction: column; min-height: 60px;">
                    <div style="flex-grow: 1;">${this.escapeHtml(comment)}</div>
                    <div style="align-self: flex-end; font-weight: bold; font-size: 20px; margin-bottom: -19px;">
                      ${this.escapeHtml(assigneeName)}
                    </div>
                    <div style="color: #888; font-size: 11px; margin-bottom: -19px; text-align: right;">${this.escapeHtml(timeStr)}</div>
                  </div>
                </div>
              `;
                // 添加到HTML内容
                this.model.conclusionHtml = htmlContent;
              }
            })
            this.$forceUpdate()
          }
        })
        .catch(error => {
          console.error('获取流程记录失败:', error)
          this.$message.error('获取流程记录失败')
        })
    },
    // 辅助方法：转义HTML特殊字符，防止XSS攻击
    escapeHtml(text) {
      if (!text) return '';
      return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    },

    getMyEvent() {
      const that = this
      that.$emit('ok')
    },
    submitAll() {
      /*      if (!this.isTotalAmountOk) {
              this.$message.warning('辅数量合计超出订货数量1%！请先修改！')
              return
            }*/
      console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
      /*this.$refs.outletquote.submitForm(this.model.id)*/
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = this.url.edit
          let method = 'put'
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                this.isAdd = false
                this.model.id = res.message
                that.$message.success(res.message)
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    submitForm() {
      //提交
      const that = this
      console.log("this.disableSubmit",this.disableSubmit)
      if (!this.disableSubmit) {
        this.submitAll()
        return
      }
      /*      if (this.tabs.activeKey == 1 && this.model.id) {
              this.activeKey = '2'
              this.tabs.activeKey = 2
              return
            }*/
      /*      if (this.tabs.activeKey == 2 && !this.isTotalAmountOk) {
              that.$message.warning('辅数量合计超出订货数量1%！请先修改！')
              return
            }*/
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            this.model.documentType = '4'
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }

          this.model.bussContractReviewDesRequire.bussContractReviewDesRequireFiles=this.$refs.bussContractReviewDesFiles.getTableData()
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                // that.$message.success(res.message);
                this.isAdd = false
                this.model.id = res.message
                /*                if (this.tabs.activeKey == 1) {
                                  this.activeKey = '2'
                                  this.tabs.activeKey = 2
                                  return
                                }
                                if (this.tabs.activeKey == 2) {
                                  this.model.id = res.message
                                  this.activeKey = '3'
                                  this.tabs.activeKey = 3
                                  this.$refs.outletquote.getFormData(this.model.id)
                                  return
                                }
                                if (this.tabs.activeKey == 3) {
                                  this.$refs.outletquote.submitForm(this.model.id)
                                  return
                                  // that.$emit('ok');
                                }*/
                that.$emit('ok');
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    addGoods: function () {
      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
      // this.$refs.selectGoodsList.add();
      // this.$refs.selectGoodsList.title = "新增";
      // this.$refs.selectGoodsList.disableSubmit = false;
    },
    goodsOk(datas) {
      let _this = this
      /*  if(this.model.bussMaterialPriceId===null || this.model.bussMaterialPriceId===""){
          return this.$message.error("请先至第一个页签（合同评审表）选择材料价格执行表")
        }*/
      postAction(this.url.productByIds, { ids: datas,priceId : this.model.bussMaterialPriceId }).then((res) => {
        let erpGoodsList = res.result
        console.log("1231313132131231231313212313132",_this.model.erpGoodsPackageList)
        const gids = _this.model.erpGoodsPackageList.map((item) => item.goodsId)
        erpGoodsList.forEach(function (item, index) {
          if (gids.indexOf(item.id) > -1) {
            return
          }
          let detail = {}
          detail.mainQuantity = 0
          detail.auxiliaryQuantity = 0
          detail.goodsId = item.id
          detail.rowKey = item.id
          detail.packageCode = item.code
          detail.packageName = item.name
          detail.customCode = item.customCode
          detail.noneSpec = item.noneSpec
          detail.coRate = item.coRate
          detail.meUnit = item.meUnit
          detail.auUnit = item.auUnit
          detail.formulaId = item.formulaId
          detail.formulaCode = item.formulaCode
          detail.formulaNumber = item.formulaNumber
          detail.formulaDefine = item.formulaDefine
          detail.formulaYear = item.formulaYear
          detail.packageType = item.packageType
          detail.packSpec = item.packSpec
          detail.packSpecNum = item.packSpecNum
          detail.quantity = item.quantity
          detail.packageVos = item.packageVos.map((item) => {
            item.proportion = 0
            item.isBrought = 0
            return item
          })
          detail.formularVos = []
          if (item.formularVos && item.formularVos.length > 0) {
            item.formularVos.forEach((fitem, findex) => {
              fitem.reviewId = _this.model.id
              fitem.rowNo = fitem.id
              fitem.price = fitem.noTaxPrice!=null&&fitem.formulaProportion!=null?Number(fitem.noTaxPrice*fitem.formulaProportion*1000).toFixed(2):0

              detail.formularVos.push(fitem)
            })
          }
          // _this.filterPackageId(item.id);
          _this.model.erpGoodsPackageList.push(detail)
        })
        _this.deepCopyGoodsList(_this.model.erpGoodsPackageList)
        _this.packagMaterials()
      })
    },
    packagMaterials(){
      let _this = this
      let datesourse =_this.model.bussOutletQuotePackageList
      _this.model.bussOutletQuotePackageList = []
      console.log("啊哈哈",this.model.erpGoodsPackageList)
      this.model.erpGoodsPackageList.forEach(function (item, index) {
        let md = datesourse.filter((j)=>j.goodsId==item.goodsId)
        let detail = {}
        detail.goodsId = item.goodsId
        detail.name = item.packageName
        detail.spec = item.noneSpec
        detail.ton = isNaN(item.mainQuantity/item.auxiliaryQuantity)?0:Number(item.mainQuantity/item.auxiliaryQuantity).toFixed(2)

        /*        // 第一组数字 + 单位(kg/g) + 单位后所有数字段
                const specReg = /^(\d+(?:\.\d+)?)\*?(kg|g)(\*(\d+(?:\.\d+)?))*$/i;

                const str = item.noneSpec;
                let grams = 0, number = 1;

                const m = str.match(specReg);
                if (m) {
                  const val  = Number(m[1]);
                  const unit = m[2].toLowerCase();
                  grams = val * (unit === 'kg' ? 1000 : 1);

                  // 提取单位后面所有数字并连乘
                  const afterUnit = str.slice(str.toLowerCase().indexOf(unit) + unit.length);
                  const nums = afterUnit.match(/\d+(?:\.\d+)?/g);
                  if (nums) {
                    number = nums.reduce((a, b) => a * Number(b), 1);
                  }
                } else {
                  // 无单位：第一组数字当grams，剩余数字连乘当number
                  const parts = str.match(/\d+(?:\.\d+)?/g);
                  if (parts) {
                    grams = Number(parts[0]);
                    number = parts.slice(1).reduce((a, b) => a * Number(b), 1);
                  }
                }*/

        detail.grams  = '';
        detail.number = '';

        console.log("哈哈哈哈哈哈哈哈哈哈哈",detail)

        detail.packageNumber1 = 0
        detail.packageNumber2 = 0
        detail.innerPackageNumber = 0
        // (Number.parseFloat(target.coRate) * Number.parseFloat(value)).toFixed(3)

        detail.packageAmount1 = 0
        detail.packageAmount2 = 0
        detail.innerPackageAmount = 0

        if(md.length>0) {
          detail.other = md[0].other
          detail.packageUnitPrice1 = md[0].packageUnitPrice1.toFixed(4)
          detail.packageUnitPrice2 = md[0].packageUnitPrice2.toFixed(4)
          detail.innerPackageUnitPrice = md[0].innerPackageUnitPrice.toFixed(4)
        }else{
          detail.other = 0
          detail.packageUnitPrice1 = 0
          detail.packageUnitPrice2 = 0
          detail.innerPackageUnitPrice = 0
        }

        if(item.mainQuantity!=null) {
          item.packageVos.forEach(function (t, i) {
            if(t.isBrought!='1') {
              if (t.packageInOutType == '2'||t.packageInOutType=='外包1') {
                console.log("ssssssssss")
                console.log("ssssssssss",detail)
                if(detail.grams==null||detail.grams==''||detail.number==null||detail.number==''){
                  detail.packageNumber1=0
                }else {
                  detail.packageNumber1 =Number(1000000/detail.grams/detail.number).toFixed(2)
                }
                if(detail.packageUnitPrice1==0&&t.noTaxPrice!=null) {
                  detail.packageUnitPrice1 = t.noTaxPrice.toFixed(4)
                }
                detail.packageAmount1 = Number(detail.packageAmount1+(detail.packageNumber1*detail.packageUnitPrice1?(detail.packageNumber1*detail.packageUnitPrice1):0)).toFixed(4)
              } else if (t.packageInOutType == '3'||t.packageInOutType=='外包2') {
                detail.packageNumber2 = 0
                if(detail.packageUnitPrice2==0&&t.noTaxPrice!=null) {
                  detail.packageUnitPrice2 = t.noTaxPrice.toFixed(4)
                }
                detail.packageAmount2 = Number(detail.packageAmount2+(detail.packageNumber2*detail.packageUnitPrice2?(detail.packageNumber2*detail.packageUnitPrice2):0)).toFixed(4)
              } else {
                if(detail.grams==null||detail.grams==''||detail.number==null||detail.number==''){
                  detail.innerPackageNumber=0
                }else {
                  detail.innerPackageNumber = Number(1000000/detail.grams).toFixed(2)
                }
                if(detail.innerPackageUnitPrice==0&&t.noTaxPrice!=null) {
                  detail.innerPackageUnitPrice = t.noTaxPrice.toFixed(4)
                }
                detail.innerPackageAmount = Number(detail.innerPackageAmount+(detail.innerPackageNumber*detail.innerPackageUnitPrice?(detail.innerPackageNumber*detail.innerPackageUnitPrice):0)).toFixed(4)

              }
            }
          })

        }

        detail.packageCost=Number(Number(detail.innerPackageAmount)+Number(detail.packageAmount2)+Number(detail.packageAmount1)+Number(detail.other)).toFixed(2)
        console.log("detailllllllllllllllllllllllll",detail)
        _this.model.bussOutletQuotePackageList.push(detail)
      })

      _this.productQuotation()
    },

    productQuotation(){
      let _this = this
      console.log("312321313",_this.model.bussOutletQuoteProductList)
      let datesourse =_this.model.bussOutletQuoteProductList
      _this.model.bussOutletQuoteProductList = []
      console.log("2131312231",_this.model.erpGoodsPackageList)
      _this.model.erpGoodsPackageList.forEach(function (item, index) {
        let md = datesourse.filter((j)=>j.goodsId==item.goodsId)
        let bc = _this.model.bussOutletQuotePackageList.filter((j)=>j.goodsId==item.goodsId)
        let detail = {}
        detail.goodsId = item.goodsId
        detail.name = item.packageName
        detail.spec = item.noneSpec
        detail.packageSpec = item.packSpec
        detail.packageMethod = item.packStyle

        detail.ton = isNaN(item.mainQuantity/item.auxiliaryQuantity)?0:Number(item.mainQuantity/item.auxiliaryQuantity).toFixed(2)
        console.log("333332",_this.model.priceType)
        if(_this.model.priceType == '0'){
          console.log("33333",_this.flag)
          detail.ywTon = item.auxiliaryQuantity
        }else {
          detail.ywTon = item.mainQuantity
        }
        /*
                detail.material =(Number((item.formularVos.reduce((acc, cur) => acc + Number(cur.price),0))*item.auxiliaryQuantity)||0).toFixed(6)
        */
        detail.material =Number(item.formularVos.reduce((acc, cur) => acc + Number(cur.price),0)).toFixed(2)
        detail.packageMaterials = bc.reduce((acc, cur) => acc + Number(cur.packageCost),0)

        if(md.length>0) {
          detail.codingFee = md[0].codingFee
          detail.midExpenses = md[0].midExpenses

          detail.landFreight = md[0].landFreight
          detail.seaFreight = md[0].seaFreight
          detail.certificate = md[0].certificate
          detail.royalty = md[0].royalty
          detail.insurancePremium = md[0].insurancePremium
          detail.commission = md[0].commission
          detail.other2 = md[0].other2

          detail.ywDamageTon = md[0].ywDamageTon
          detail.ywisCompliantPolicies = md[0].ywisCompliantPolicies
          detail.ywTonPrice = md[0].ywTonPrice
          console.log("buggggggg",_this.flag,md[0].ywPiecePrice)
          if(_this.flag==1){
            detail.ywPiecePrice = Number(md[0].ywPiecePrice).toFixed(2)
            if(index==_this.model.erpGoodsPackageList.length-1){
              _this.flag=0
            }
          }else {
            detail.ywPiecePrice = Number((md[0].ywTonPrice * item.coRate)).toFixed(2)
          }
          if (_this.model.priceType == '0'){
            detail.ywActualQuote=detail.ywTonPrice
          }else {
            detail.ywActualQuote = detail.ywPiecePrice
          }
        }else{
          detail.codingFee = 0
          detail.midExpenses = 0
          detail.landFreight = 0
          detail.seaFreight = 0
          detail.certificate = 0
          detail.royalty = 0
          detail.insurancePremium = 0
          detail.commission = 0
          detail.other2 = 0

          detail.ywDamageTon = 0
          detail.ywActualQuote = 0

          detail.ywisCompliantPolicies = '1'
        }
        console.log("1222+++++++++++++++++++",_this.model,_this.model.taxRate,_this.model.exchangeRate)
        detail.total = (Number(detail.material)+Number(detail.packageMaterials)+Number(detail.midExpenses)+Number(detail.codingFee)).toFixed(2)
        detail.exWorksPrice = ((Number(detail.material)+Number(detail.packageMaterials)+Number(detail.midExpenses)+Number(detail.codingFee))*_this.model.taxRate/_this.model.exchangeRate).toFixed(2)
        console.log("123+++++++",(Number(detail.material)+Number(detail.packageMaterials)+Number(detail.midExpenses)),_this.model.taxRate,_this.model.exchangeRate,(Number(detail.material)+Number(detail.packageMaterials)+Number(detail.midExpenses))*_this.model.taxRate/_this.model.exchangeRate)
        detail.total2 = (Number(detail.exWorksPrice)+Number(detail.landFreight)+Number(detail.seaFreight)+Number(detail.certificate)+Number(detail.royalty)+Number(detail.insurancePremium)+Number(detail.commission)+Number(detail.other2)).toFixed(2)
        /*detail.ywTonPrice = (detail.total2*1.06).toFixed(6)*/

        _this.model.bussOutletQuoteProductList.push(detail)
      })
      this.model.totalPrice=0
      this.model.bussOutletQuoteProductList.forEach(item=>{
          if(_this.model.priceType == '0'){
            _this.model.totalPrice=_this.model.totalPrice+item.ywTon*item.ywTonPrice
          }else {
            _this.model.totalPrice=_this.model.totalPrice+item.ywTon*item.ywPiecePrice
          }
        }
      )
      console.log("sasdadasdada啊啊啊啊啊啊啊啊啊啊",this.model.bussOutletQuoteProductList)
    },
    getGoodsById(id) {
      let _this = this
      let ids = []
      ids.push(id)
      /*if(this.model.bussMaterialPriceId===null || this.model.bussMaterialPriceId===""){
        return this.$message.error("请先至第一个页签（合同评审表）选择材料价格执行表")
      }*/
      postAction(this.url.productByIds, { ids: ids, priceId : this.model.bussMaterialPriceId }).then((res) => {
          let erpGoods = res.result[0]
          const dataSource = [..._this.model.erpGoodsPackageList]
          let record = dataSource.find((item) => item.goodsId == id)
          console.log(res.result, erpGoods, record, '获取物料')
          record.packageVos = [...erpGoods.packageVos]
          record.formularVos = []
          if (erpGoods.formularVos && erpGoods.formularVos.length > 0) {
            record.formularVos = erpGoods.formularVos.map((item) => {
              return { ...item, rowNo: item.materialId + Math.random() }
            })
          }
          _this.model.packageList = record.packageVos
          _this.formularDetailList = record.formularVos
          _this.model.erpGoodsPackageList = dataSource
          //_this.onSelectChange(_this.selectedRowKeys, _this.model.erpGoodsPackageList)
          _this.deepCopyGoodsList(dataSource)
        }
      )
    },
    packageOk(datas) {
      console.log(datas, this.selectedProduct)
      const idList = datas.map(item => item.id)
      this.model.packageList = []
      const map = new Map(datas.map(item => [item.code, item]));
      // let packageVos = []
      // if (this.selectedProduct.packageVos && this.selectedProduct.packageVos.length > 0) {
      //   packageVos = this.selectedProduct.packageVos
      // }
      let _this = this
      /* if(this.model.bussMaterialPriceId===null || this.model.bussMaterialPriceId===""){
         return this.$message.error("请先至第一个页签（合同评审表）选择材料价格执行表")
       }*/
      postAction(this.url.packageByIds, { ids: idList,priceId : this.model.bussMaterialPriceId }).then((res) => {
        let resVos = res.result
        console.log(res.result, '新增包材')
        if (resVos && resVos.length > 0) {
          resVos.forEach((item) => {
            let packageObj = {}
            packageObj.goodsId = _this.selectedProduct.goodsId
            packageObj.packageId = item.packageId
            packageObj.packageCode = item.packageCode
            packageObj.packageName = item.packageName
            packageObj.noneSpec = item.noneSpec
            packageObj.packSpec = item.packSpec
            packageObj.size = item.size
            packageObj.materialQuality = item.materialQuality
            packageObj.detailNo = item.packageId + Math.random()
            packageObj.requirements = item.packRequire
            packageObj.isPattern = item.isPattern
            //packageObj.proportion = item.proportion
            packageObj.taxPrice = item.taxPrice
            packageObj.noTaxPrice = item.noTaxPrice
            packageObj.isBrought = 0
            packageObj.patternFile= map.get(item.packageCode).patternFile
            this.selectedProduct.packageVos.push(packageObj)
          })
          // this.selectedProduct.packageVos = packageVos
          this.model.packageList = [...this.selectedProduct.packageVos]
          console.log('新增包材', this.selectedProduct, this.model.packageList)
          _this.deepCopyGoodsList(_this.model.erpGoodsPackageList)
          _this.$forceUpdate()
        }
      })
    },
    addPackage() {

      if (this.selectedRows[0].goodsId==null) {
        this.$message.warning('请先选择产品')
        return
      }

      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(() => {
        this.$refs.selectPackageList.add()
      })
    },
    filterPackageId(goodsId) {
      this.model.erpGoodsPackageList = this.model.erpGoodsPackageList.filter(function (item) {
        return item.goodsId !== goodsId
      })
    },
    onCellChange(record, dataIndex, value) {
      console.log(this.model.erpGoodsPackageList)
      console.log(record)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        target[dataIndex] = value
        console.log('isProduction', value, this.erpPackageListTmp)
        if (dataIndex == 'isProduction') {
          //生产
          if (value == '1') {
            const tmpTarget = this.erpPackageListTmp.find((item) => item.packageCode === record.packageCode)
            console.log(tmpTarget, 'tmpTarget')
            if (tmpTarget.formularVos && tmpTarget.formularVos.length > 0) {
              /*              this.formularDetailList = tmpTarget.formularVos
                            target.formularVos = [...tmpTarget.formularVos]
                            this.model.packageList = tmpTarget.packageVos*/
              target.packageVos = [...tmpTarget.packageVos]
              this.model.erpGoodsPackageList = dataSource
              //this.onSelectChange(target.rowKey, this.model.erpGoodsPackageList)
            } else {
              //获取产品物料关联的数据
              this.getGoodsById(target.goodsId)
            }
          } else {
            //不生产
            /*            this.formularDetailList = []
                        this.model.packageList = []
                        target.formularVos = []
                        target.packageVos = []*/
            this.model.erpGoodsPackageList = dataSource
          }
        } else {
          this.model.erpGoodsPackageList = dataSource
          this.deepCopyGoodsList(dataSource)
        }
      }
    },
    deepCopyGoodsList(source) {
      this.erpPackageListTmp = []
      if (source && source.length > 0) {
        source.forEach((item) => {
          let target = {}
          target = Object.assign({}, item)
          target.formularVos = []
          if (item.formularVos && item.formularVos.length > 0) {
            item.formularVos.forEach((fitem) => {
              let f = Object.assign({}, fitem)
              target.formularVos.push(f)
            })
          }
          target.packageVos = []
          if (item.packageVos && item.packageVos.length > 0) {
            item.packageVos.forEach((pitem) => {
              let p = Object.assign({}, pitem)
              target.packageVos.push(p)
            })
          }
          this.erpPackageListTmp.push(target)
        })
      }
      console.log(this.erpPackageListTmp, '深度copy')
    },
    onMainQuantityCellChange(record, dataIndex, value) {
      console.log(this.model.erpGoodsPackageList)
      console.log(record)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        //修改主数量
        target[dataIndex] = value
        //计算辅数量
        target.auxiliaryQuantity = (Number.parseFloat(target.coRate) * Number.parseFloat(value)).toFixed(3)
        this.model.erpGoodsPackageList = dataSource
        this.deepCopyGoodsList(dataSource)
        this.checkIsTotalAmountOk()
        this.packagMaterials()
      }
    },
    checkIsTotalAmountOk() {
      if (this.model.erpGoodsPackageList && this.model.erpGoodsPackageList.length > 0) {
        let totalAmount = this.model.erpGoodsPackageList.reduce((sum, item) => {
          return parseFloat(sum) + parseFloat(item.auxiliaryQuantity)
        }, 0)
        this.model.totalProductAmount = Number.parseFloat(totalAmount).toFixed(2)

        /*        if (
                  this.model.totalProductAmount > this.model.weight * 1.01 ||
                  this.model.totalProductAmount < this.model.weight * (1 - 0.01)
                ) {
                  console.log(
                    '计算辅数量合计=======',
                    this.model.erpGoodsPackageList,
                    this.model.totalProductAmount,
                    totalAmount
                  )
                  // this.$message.warning('辅数量合计不能超过订货数量的1%！')
                  this.isTotalAmountOk = false
                } else {
                  this.isTotalAmountOk = true
                }*/
        this.$forceUpdate()
      } else {
        console.log('没有物料')
        this.model.totalProductAmount = 0
        this.isTotalAmountOk = false
      }
    },
    onBussOutletQuoteChange(record, dataIndex, value) {
      const dataSource = [...this.model.bussOutletQuotePackageList]
      const target = dataSource.find((item) => item.goodsId === record.goodsId)
      if(dataIndex=='innerPackageUnitPrice'||dataIndex=='packageUnitPrice2'||dataIndex=='packageUnitPrice1'){
        value=Number(value).toFixed(4)
      }
      target[dataIndex] = value
      if(dataIndex=='grams'||dataIndex=='number') {
        target.packageNumber1 = Number(1000000 / target.grams / target.number).toFixed(2)
        target.innerPackageNumber = Number(1000000 / target.grams).toFixed(2)
      }
      target.innerPackageAmount =
        target.innerPackageNumber != '' && target.innerPackageUnitPrice != ''
          ? (Number(target.innerPackageNumber) * Number(target.innerPackageUnitPrice)).toFixed(4)
          : 0;

      target.packageAmount2 =
        target.packageNumber2 != '' && target.packageUnitPrice2 != ''
          ? (Number(target.packageNumber2) * Number(target.packageUnitPrice2)).toFixed(4)
          : 0;

      target.packageAmount1 =
        target.packageNumber1 != '' && target.packageUnitPrice1 != ''
          ? (Number(target.packageNumber1) * Number(target.packageUnitPrice1)).toFixed(4)
          : 0;
      /*target.other=value*/
      target.packageCost=Number(Number(target.innerPackageAmount)+Number(target.packageAmount2)+Number(target.packageAmount1)+Number(target.other)).toFixed(2)
      console.log("修改",target,record,dataIndex,value)
      this.productQuotation()
    },
    onBussOutletQuoteProductChange(record, dataIndex, value) {
      const dataSource = [...this.model.bussOutletQuoteProductList]
      const target = dataSource.find((item) => item.goodsId === record.goodsId)
      target[dataIndex]=value
      console.log("修改",target)
      this.productQuotation()
    },
    changeYwPiecePrice(record, dataIndex, value) {
      const dataSource = [...this.model.bussOutletQuoteProductList]
      const target = dataSource.find((item) => item.goodsId === record.goodsId)
      target[dataIndex]=value
      console.log("修改",target)
      this.flag=1
      this.productQuotation()
    },
    onFormularCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === record.productId)
      const formularSource = target.formularVos
      const formulartarget = formularSource.find((item) => item.rowNo === record.rowNo)
      if(dataIndex == 'formula'){
        formulartarget.formulaProportion=value
        //TODO
        getAction(this.url.getFormulaResult, { formulaAttribute: '1', formulaProportion: formulartarget.formulaProportion, materialId: formulartarget.materialId }).then(res=>{
          if (res.success) {
            formulartarget.actualQuantity=res.result
          } else {
            formulartarget.actualQuantity=0
          }
        }).finally(() =>{
          formulartarget.price=Number(formulartarget.actualQuantity*formulartarget.noTaxPrice).toFixed(2)
          this.model.erpGoodsPackageList = dataSource
          this.formularDetailList = formularSource
        })


      } else if (dataIndex == 'taxPrice') {
        formulartarget.taxPrice = value
        formulartarget.noTaxPrice = Number(value/1.13).toFixed(2)
        formulartarget.price=Number(formulartarget.noTaxPrice*formulartarget.actualQuantity).toFixed(2)
        this.model.erpGoodsPackageList = dataSource
        this.formularDetailList = formularSource
      } else if (dataIndex == 'isSelfProvided') {
        formulartarget.isSelfProvided = value

        this.model.erpGoodsPackageList = dataSource
        this.formularDetailList = formularSource
      }


      this.deepCopyGoodsList(dataSource)
      this.productQuotation()
      /*if (record) {
        formulartarget[dataIndex] = value
        if (dataIndex == 'formula') {
          postAction('/base/erpGoodsFormulaDetail/compute/formula', {
            list: formularSource,
            detail: formulartarget,
          }).then((res) => {
            if (res.success) {
              this.$set(formulartarget, 'actualQuantity', res.result)
              formulartarget.noTaxPrice = (Number.parseFloat(formulartarget.taxPrice) / this.tax).toFixed(6)
              formulartarget.price = (
                Number.parseFloat(formulartarget.noTaxPrice) * Number.parseFloat(formulartarget.actualQuantity)
              ).toFixed(2)
              formulartarget.rowNo = formulartarget.rowNo + 1
              this.formularDetailList = formularSource
              console.log('计算完的值', this.formularDetailList)
              this.model.erpGoodsPackageList = dataSource
              console.log('修改后：', this.model.erpGoodsPackageList)
              let materilPrice = this.formularDetailList.reduce((sum, item) => {
                return parseFloat(sum) + parseFloat(item.price)
              }, 0)
              materilPrice = materilPrice ? parseFloat(materilPrice).toFixed(2) : 0
              console.log('原料成本：', materilPrice, record.productId)
              this.$refs.outletquote.calcMaterial(record.productId, materilPrice)
              this.deepCopyGoodsList(dataSource)
            }
          })
        } else {
          formulartarget.noTaxPrice = (Number.parseFloat(formulartarget.taxPrice) / this.tax).toFixed(6)
          formulartarget.price = (
            Number.parseFloat(formulartarget.noTaxPrice) * Number.parseFloat(formulartarget.actualQuantity)
          ).toFixed(2)
          formulartarget.rowNo = formulartarget.rowNo + 1
          this.formularDetailList = formularSource
          console.log('计算完的值', this.formularDetailList)
          this.model.erpGoodsPackageList = dataSource
          console.log('修改后：', this.model.erpGoodsPackageList)
          let materilPrice = this.formularDetailList.reduce((sum, item) => {
            return parseFloat(sum) + parseFloat(item.price)
          }, 0)
          materilPrice = materilPrice ? parseFloat(materilPrice).toFixed(2) : 0
          console.log('原料成本：', materilPrice, record.productId)
          this.$refs.outletquote.calcMaterial(record.productId, materilPrice)
          this.deepCopyGoodsList(dataSource)
        }
      }*/
    },
    onChildCellChange(record, dataIndex, value) {
      console.log('关联包材修改')
      console.log(this.model.erpGoodsPackageList, this.selectedRows[0])
      console.log(record, dataIndex, value)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === this.selectedRows[0].goodsId)

      const packageSource = target.packageVos
      const packagetarget = packageSource.find((item) => item.packageCode === record.packageCode)
      // console.log(target,key,dataIndex,value)
      if (record) {
        packagetarget[dataIndex] = value
        this.model.packageList = packageSource
        this.model.erpGoodsPackageList = dataSource
        this.deepCopyGoodsList(dataSource)
      }
      console.log(this.model.erpGoodsPackageList)
    },
    onDelete(key) {
      const dataSource = [...this.model.erpGoodsPackageList]
      this.model.erpGoodsPackageList = dataSource.filter((item) => item.goodsId !== key)
      if(this.selectedRowKeys==key) {
        this.model.packageList = []
        this.formularDetailList = []
        this.selectedRowKeys = []
        this.selectedRows = [{lossRate:'',proportions:'',isIncrease:'0'}]

      }
      const quoteProductList = [...this.model.bussOutletQuoteProductList]
      this.model.bussOutletQuoteProductList = quoteProductList.filter((item) => item.goodsId !== key)
      const quotePackageList = [...this.model.bussOutletQuotePackageList]
      this.model.bussOutletQuotePackageList = quotePackageList.filter((item) => item.goodsId !== key)
      this.deepCopyGoodsList(this.model.erpGoodsPackageList)
      this.checkIsTotalAmountOk()
    },
    onDeleteBC(key){
      const dataSource = [...this.model.packageList]
      this.model.packageList = dataSource.filter((item) => item.id !== key.id)
      this.selectedProduct.packageVos = dataSource.filter((item) => item.id !== key.id)
    },
    onDeletePackage(record) {
      const dataSource = [...this.selectedProduct.packageVos]
      this.selectedProduct.packageVos = dataSource.filter((item) => item.detailNo !== record.detailNo)
      this.model.packageList = this.selectedProduct.packageVos
      console.log(this.model.erpGoodsPackageList, this.selectedProduct.packageVos, this.model.packageList)
      this.deepCopyGoodsList(this.model.erpGoodsPackageList)
      this.$forceUpdate()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      if (this.selectedRows.length > 0 && this.selectedRows[0] != null) {
        const key = 'goodsId'
        this.selectedRowKeys = [selectedRowKeys.filter((item) => item !== this.selectedRowKeys[0])[0]]
        this.selectedRows = [selectedRows.filter((item) => item[key] !== this.selectedRows[0][key])[0]]
      } else {
        this.selectedRowKeys = [selectedRowKeys[0]]
        this.selectedRows = [selectedRows[0]]
      }

      this.showPatternFlag = false
      console.log(this.selectedRows, 'this.selectedRows')

      if (this.selectedRows[0] != null) {
        this.selectedProduct = this.selectedRows[0]
        const dataSource = [...this.model.erpGoodsPackageList]
        const target = dataSource.find((item) => item.goodsId === this.selectedRows[0].goodsId)
        console.log('target', target)
        console.log('this.selectedProduct', this.selectedProduct)
        //关联物料包材信息
        if (!this.selectedProduct.packageVos || this.selectedProduct.packageVos.length == 0) {
          this.selectedProduct.packageVos = []

          if (target.packageVos != null && target.packageVos.length > 0) {
            this.model.packageList = target.packageVos
          } else {
            this.model.packageList = []
          }
          this.selectedProduct.packageVos = this.model.packageList
        } else {
          this.model.packageList = this.selectedProduct.packageVos
        }
        if (!this.selectedProduct.packageVos || this.selectedProduct.packageVos.length == 0) {
          this.selectedProduct.packageVos = []

          if (target.packageVos != null && target.packageVos.length > 0) {
            this.model.packageList = target.packageVos
          } else {
            this.model.packageList = []
          }
          this.selectedProduct.packageVos = this.model.packageList
        } else {
          this.model.packageList = this.selectedProduct.packageVos
        }

        let formularVos = target.formularVos || this.selectedProduct.formularVos
        this.formularDetailList = []
        if (formularVos && formularVos.length > 0) {
          formularVos.forEach((fitem, index) => {
            let fdetail = {}
            fdetail.rowNo = fitem.id
            fdetail.materialId = fitem.materialId
            fdetail.materialCode = fitem.materialCode
            fdetail.materialName = fitem.materialName
            fdetail.materialSpec = fitem.materialSpec
            fdetail.isSelfProvided = fitem.isSelfProvided
            //fdetail.isSelfProvided_dictText =  fdetail.isSelfProvided=='0'?'否':'是'
            fdetail.formulaProportion = fitem.formulaProportion
            fdetail.taxPrice = fitem.taxPrice
            fdetail.noTaxPrice = fitem.noTaxPrice
            fdetail.price = fitem.price
            fdetail.id = fitem.id
            fdetail.productId = fitem.productId
            fdetail.formulaId = fitem.formulaId

            //fdetail.isClientOwn = fitem.isClientOwn
            fdetail.actualQuantity = fitem.actualQuantity
            // fdetail.computingFormula = fitem.computingFormula
            // fdetail.formula = fitem.formula

            this.formularDetailList.push(fdetail)
          })

          console.log('获取物料BOM：', this.formularDetailList)
        }
      }
    },
    handleCorrelation(record) {
      this.goodsId = record.goodsId
      this.$refs.selectFormulaList.add()
      this.$refs.selectFormulaList.title = '选择配方'
      this.$refs.selectFormulaList.disableSubmit = false
    },
    formulasOk(datas) {
      console.log(datas)
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.goodsId === this.goodsId)
      if (target) {
        target['formulaId'] = datas.id
        target['formulaYear'] = datas.year
        target['formulaName'] = datas.name
        target['formulaCode'] = datas.code
        target['formulaNo'] = datas.no;
        this.model.erpGoodsPackageList = dataSource
        this.deepCopyGoodsList(dataSource)
      }
      console.log(this.model.erpGoodsPackageList)
    },
    handleEditClosed(event) {
      let { $table, row, column } = event

      let field = column.property
      let cellValue = row[field]
      // 判断单元格值是否被修改
      if ($table.isUpdateByRow(row, field)) {
        // 校验当前行
        $table.validate(row).then((errMap) => {
          // 校验通过
          if (!errMap) {
            console.log('即时保存数据：', row)
            this.savePattern(row)
          }
        })
      }
    },

    handleFileChange(event) {
      const file = event.target.files[0] // 获取文件
      if (file) {
        // 处理文件，例如上传到服务器
        this.uploadFile(file)
      }
    },
    uploadFile(file) {
      // 这里编写文件上传的逻辑
      console.log('Uploading file...', file)
      // 示例中仅打印文件信息，实际应用中需要编写文件上传代码
      const formData = new FormData()
      formData.append('file', file)

      // 使用axios发送文件
      postAction('/sys/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
        .then((response) => {
          console.log('response')
          console.log(response.message)
          let detail = {}
          detail.patternId = this.packageId
          detail.name = response.message
          postAction('/pattern/erpGoodsPattern/addPattern', detail).then((res) => {
            this.$message.success(res.message)
          })
        })
        .catch((error) => {
          console.error(error)
        })
    },
    // addProc(){
    //   if(this.procSelectRows.length>0){
    //     const rows = this.procSelectRows
    //     this.$nextTick(()=>{
    //       this.contract = rows[0];
    //       this.add();
    //     })
    //   }
    // },
  },
}
</script>
<style lang="stylus" scoped>

.rich-text-container {
  min-height: 127px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  overflow-y: auto;
  background-color: #fff;
  transition: all 0.3s;
}

.rich-text-container:hover {
  border-color: #40a9ff;
}

.rich-text-content {
  padding: 4px 11px;
}

.rich-text-container.disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: rgba(0, 0, 0, 0.65);
  cursor: not-allowed;
  user-select: none;
}

.rich-text-container.disabled:hover {
  border-color: #d9d9d9;
}

.mytable >>> .ant-table-thead > tr > th, .ant-table-tbody > tr > td {
  padding: 2px 2px;
  overflow-wrap: break-word;
}
.mytable >>> .ant-table-tbody .ant-table-row td {
  padding-top: 2px;
  padding-bottom: 2px;
}
.mytable{
  .ant-table {
    min-height: 200px !important;
    overflow: scroll;
  }
}
.mycard{
  padding: 2px 2px;
  //height:300px;

}
.mycard .ant-card-body{
  padding: 2px 2px;
}

/* 禁用文本区域的样式 */
.disabled-textarea[disabled] {
  color: #000 !important;  /* 黑色字体 */
  font-weight: bold !important;  /* 加粗 */
  background-color: #f5f5f5 !important;  /* 保持灰色背景表示禁用状态 */
  cursor: not-allowed !important;  /* 禁用光标 */
  opacity: 1 !important;  /* 防止浏览器默认降低透明度 */
}

/* 如果需要修改 placeholder 的颜色 */
.disabled-textarea[disabled]::placeholder {
  color: #999 !important;
  font-weight: normal !important;
}
.mycard >>> .ant-input-disabled {
  color: #000 !important;
  font-weight: bold !important;
}
</style>
